Group objects with matching properties into Lists

Baxter picture Baxter · Apr 3, 2012 · Viewed 14k times · Source

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.)

Answer

Jon Skeet picture Jon Skeet · Apr 3, 2012

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);
    }
}