我们有对象:
Foo a = new Foo;
a.Prop1 = XX;
a.Prop2 = YY;
a.Prop3 = 12;
Foo b = new Foo;
b.Prop1 = XX;
b.Prop2 = ZZ;
b.Prop3 = 3;
Foo c = new Foo;
c.Prop1 = FF;
c.Prop2 = DD;
c.Prop3 = 3;
我们有一个列表=
List<Foo> MyList= new List<Foo>()
并将所有这些对象添加到列表中
在遍历该列表时:
foreach(Foo _foo in Mylist)
{
// I want to get the objects whose Prop1 value is
// the same and add those to another list, what I want
// to do exactly is actually grouping based on a property.
}
最佳答案
您可以使用GroupBy
实现此目的:
var myOtherList = list.GroupBy(x => x.Prop1)
.Where(x => x.Count() > 1)
.ToList();
myOtherList
现在每个Prop1
包含一个组,该组会多次出现,并且所有具有此Prop1
的项目。如果您不在乎这些组,而仅在乎它们包含的项目,则可以按以下方式更改查询:
var myOtherList = list.GroupBy(x => x.Prop1)
.Where(x => x.Count() > 1)
.SelectMany(x => x)
.ToList();
关于c# - 对于每次迭代,在类中获取相同的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17852234/