简体   繁体   English

如何使用 C# 对列表中的相似项进行分组?

[英]How to group similar items in a list using C#?

I been trying to tackle this for half a day now, with no luck.我已经尝试解决这个问题半天了,但没有运气。 I have a bunch of objects in a list.我在列表中有一堆对象。 I want to sort the list by equal y values, which I did here:我想按相等的 y 值对列表进行排序,我在这里做了:

ListOfObjects.Sort((y1,y2) => y1.y.CompareTo(y2.y));

But now I want to separate all objects with equal y values in new lists.但是现在我想在新列表中将所有具有相同 y 值的对象分开。 How would I approach this?我将如何处理这个问题?

You can use GroupBy .您可以使用GroupBy

var groups = ListOfObjects.GroupBy(x => x.y);

And if you explicitly want lists:如果您明确想要列表:

var lists = ListOfObjects.GroupBy(x => x.y).Select(x => x.ToList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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