var groupedCustomerList = userList
.GroupBy(u => u.GroupID)
.Select(grp => grp.ToList())
.ToList();
Your group statement will group by group ID. For example, if you then write:
foreach (var group in groupedCustomerList)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var user in group)
{
Console.WriteLine(" {0}", user.UserName);
}
}
that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement>
which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.
For type
public class KeyValue
{
public string KeyCol { get; set; }
public string ValueCol { get; set; }
}
collection
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" }
};
our linq query look like below
var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };
or for array instead of list like below
var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With