Group objects of the same type C #

I have a list of objects that are disabled or uniquely identified by one of their properties: "ID". I need to group all objects with different identifiers that will have the rest of the properties.

Example: Obj has the properties "ID", "E1", "E2", "E3". Please note that these are all properties of Obj.

I know that the identifiers are different for all List of Obj, but would like to group if E1, E2 and E3 are the same for different Obj. So I would have an Obj array with the same E1, E2, E3, but with different identifiers.

What is the easiest way to handle this in C #, any ideas?

+3
source share
3 answers

Well, something like this will work with LINQ:

var groups = collections.GroupBy(x => new { x.E1, x.E2, x.E3 });

, . :

var groups = collections.GroupBy(x => new { x.E1, x.E2, x.E3 });
foreach (var group in groups)
{
    Console.WriteLine("Key: {0}", group.Key);
    foreach (var item in group)
    {
        Console.WriteLine("  ID: {0}", item.ID);
    }
}
+9

/ . .

0

Linq .

public class YourClass
{
    public string ID { get; set; }
    public string E1 { get; set; }
    public string E2 { get; set; }
    public string E3 { get; set; }
}

public static YourClass[] GetClassArray(IEnumerable<YourClass> objects)
{
    return objects.OrderBy<YourClass, string>(c => c.E1)
                  .ThenBy<YourClass, string>(c => c.E2)
                  .ThenBy<YourClass, string>(c => c.E3)
                  .ThenBy<YourClass, string>(c => c.ID)
                  .ToArray<YourClass>();
}
0

All Articles