Wednesday, August 31, 2016

Linq - Group by into an array

LINQ has lot of capability that we seldom use.For example sometime we need to group a column into a string array or collection of some sort like say list based on another column.

Here I will demonstrate same into an array.

For purpose of demonstration I will create a class in some existing project

  public class KeyValue
    {
        public string KeyCol { get; set; }
        public string ValueCol { get; set; }
    }
 
Now I will create simple array of type 'KeyValue' just created.

  var wordList = new Model.DTO.KeyValue[] {
                new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
                new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
                new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
                new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
                new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
                new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
            };

Lets build a linq query on this collection(Array).Query groups 'KeyCol' property based on 'ValueCol' into group 'g' i.e. means g is collection of 'KeyCol'

            var query =from m in wordList
                     group m.KeyCol by m.ValueCol into g
                     select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };

You can check resultset my looping  'query' 

    foreach (var rec in query)
    {
        var name = rec.Name;
        var strArray = rec.KeyCols;
    }

e.g in loop above when 'name' becomes 'value1' ,'strArray' will have value string[]{'key1','key2'} and so on.

we can further generalize this query to create object array in group by.

No comments:

Post a Comment