Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group objects with matching properties into Lists

I have a List of objects in C#. All the objects contain properties code1 and code2 (among other properties).

Example:

List -> object = id, name, code1, code2, hours, amount.

There are 31 possible code1 values. There are 10 possible code2 values.

I need to group together all objects having the same code1 and code2 values (the unique combination) into their own Lists which would be saved within a parent list (so that each individual list could be iterated over later.)

like image 834
Baxter Avatar asked Apr 03 '12 17:04

Baxter


2 Answers

Sounds like you want something like:

var groups = list.GroupBy(x => new { x.code1, x.code2 });

// Example of iterating...
foreach (var group in groups)
{
    Console.WriteLine("{0} / {1}:", group.Key.code1, group.Key.code2);
    foreach (var item in group)
    {
        Console.WriteLine("  {0} ({1})", item.id, item.name);
    }
}
like image 110
Jon Skeet Avatar answered Nov 19 '22 16:11

Jon Skeet


Enumerable extensions is your friend (are* your friends? :)

var groups = lists.GroupBy(item => new { item.code1, item.code2 });

And....the legendary Skeet hit post before I did, the SHAME!

Time to one up Skeet (ha, right). You could also group your common items in a dictionary.

var mapping = list
  .GroupBy(item => new { item.code1, item.code2 })
  .ToDictionary(g => g.Key, g => g.ToList());

Now mapping is a Dictionary<anon{code1, code2}, List<YourObject>>. Of course you could leave off the ToList for the value, and the value type of the dictionary would be an IGrouping, which is an IEnumerable.

You could also use ToLookup

var lookup = list.ToLookup(item => new { item.code1, item.code2 });

The result is an ILookup which has a key of the key Type given, and is an IEnumerable of the list type used. It's not a dictionary, but can be used similarly.

like image 26
payo Avatar answered Nov 19 '22 14:11

payo