I have a list of objects that are keyed off or identified uniquely by one of their properties say "ID". I need to group all the objects of different ID's that will have rest of properties the same.
Example: Obj has properties "ID", "E1", "E2" , "E3". Note these are all properties of the Obj.
I know ID's are different for all List of Obj's, but would like to group if E1,E2 and E3 are same for different Obj's. So I开发者_如何学JAVA would have array of Obj's that have same E1,E2,E3 but different ID's.
What's the easiest way of handling this in C#, any ideas?
Well, something like this would work with LINQ:
var groups = collections.GroupBy(x => new { x.E1, x.E2, x.E3 });
That will give you a sequence of groupings you can iterate over. For example:
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);
}
}
Implement an Interface of common properties/methods between the objects. Use the interface type for interaction.
Linq sounds good to me.
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>();
}
精彩评论