Reputation: 1626
We have objects:
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;
And we have a list = List<Foo> MyList= new List<Foo>()
And all these objects are added to the list
While iterating through that list:
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.
}
Upvotes: 1
Views: 119
Reputation: 174309
You could use GroupBy
to achieve this:
var myOtherList = list.GroupBy(x => x.Prop1)
.Where(x => x.Count() > 1)
.ToList();
myOtherList
now contains one group per Prop1
that appears multiple times and all items that have this Prop1
.
If you don't care about the groups but only about the items they contain, you can change the query like this:
var myOtherList = list.GroupBy(x => x.Prop1)
.Where(x => x.Count() > 1)
.SelectMany(x => x)
.ToList();
Upvotes: 4
Reputation: 1122
If you are free to use LINQ, this would accomplish..
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")));
Upvotes: 0
Reputation: 22794
You could do it with LINQ too:
Classlist.Where(x => x == whatever).ToList();
Upvotes: 0
Reputation: 14618
Firstly, when you say classes
i think you mean objects
or instances of that class.
List<YourType> types = new List<YourType>();
List<YourType> types2 = new List<YourType>();
foreach(YourType yType in types)
{
if(yType.Foo == "XX")
{
types2.Add(yType);
}
}
Upvotes: 2