1

我们有对象:

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.
}
4

4 回答 4

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();
于 2013-07-25T08:05:33.840 回答
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);
    }
}
于 2013-07-25T08:02:44.573 回答
0

你也可以用 LINQ 做到这一点:

Classlist.Where(x => x == whatever).ToList();
于 2013-07-25T08:04:53.163 回答
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")));
于 2013-07-25T08:07:44.383 回答