我们有对象:
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 = 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.
}
答案 0 :(得分:4)
您可以使用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();
答案 1 :(得分:2)
首先,当你说classes
我认为你的意思是objects
或该类的实例时。
List<YourType> types = new List<YourType>();
List<YourType> types2 = new List<YourType>();
foreach(YourType yType in types)
{
if(yType.Foo == "XX")
{
types2.Add(yType);
}
}
答案 2 :(得分:0)
您也可以使用LINQ:
Classlist.Where(x => x == whatever).ToList();
答案 3 :(得分:0)
如果您可以自由使用LINQ,这将完成..
List<FooClass> originalList = new List<FooClass>(); // your original list containing the objects
List<FooClass> newList = new List<FooClass>(); // Destination list where you want to keep adding the matching objects
newList.AddRange(originalList.Where(el => string.Equals(el.Foo, "xx")));