简体   繁体   中英

Get list of list with same complex objects

considering the following List of objects:

Obj1 - X = 1, Y = 1
Obj2 - X = 1, Y = 1
Obj3 - X = 1, Y = 1
Obj4 - X = 2, Y = 1
Obj5 - X = 2, Y = 1

I want to achieve this (two lists with the same objects):

L1 - Obj1, Obj2, Obj3
L2 - Obj4, Obj5

I did this lambda expression, but it doesn't works:

var grouped = ListOfItens.GroupBy(x => ListOfItens.Where(y => new { y.X, y.Y} == new { x.X, x.Y }));

I'm pretty sure that the problem is in my Group by condition, but I can't figure out what it is!

Thanks!

You either have to provide a custom IEqualityComparer<YourClass> for the overload of Enumerable.GroupBy , override Equals + GetHashCode in that class or use an anonymous type for the GroupBy which works if the properties' types override Equals + GetHashCode (which is the case for System.Int32 ).

Assuming that you want to create a List<List<YourClass>> :

List<List<YourClass>> grouped = ListOfItens
    .GroupBy(x => new {x.X, x.Y})
    .Select(g => g.ToList())
    .ToList();

您必须以这种方式使用GroupBy

var grouped = ListOfItens.GroupBy(y => new { y.X, y.Y});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM