Foreach迭代,在类中获取相同的值

时间:2013-07-25 07:58:36

标签: c# linq

我们有对象:

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

4 个答案:

答案 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")));