Reputation: 337
I have a List consisting of the Following Objects
List<Person> PersonList
The Person class
class Person
{
public int PersonId{get;set;}
public string PersonName{get;set;
public int Age {get;set;}
}
I have another List that contains a List of Ages that I am interested in, like 12, 14, 16, 24 etc.
List<int> AgeList
I want to compare the Age of the PersonList
with the ages found in AgeList
and IF found, store it in a separate Lists based upon each group. For example People belonging to Age 12 should be in a different List, Age 14 in a different List and So on..
Upvotes: 1
Views: 1270
Reputation: 711
This is some quick code for you, without LINQ. First you create new list of type Person
, then loop over your Person list, and for every person you check if age is the same as one in your age list.
List<Person> finalList=new List<Person>();
foreach (var a in PersonList)
{
foreach (var b in AgeList)
{
if (a.Age==b)
{
finalList.Add(a);
break;
}
}
}
Upvotes: 1
Reputation: 31322
LINQ solution:
List<Person> personAgeList = PersonList.Where(p => AgeList.Contains(p.Age)).ToList();
Upvotes: 1
Reputation: 2202
List<Person> data = new List<Person>();
List<int> ages = new List<int>();
List<Person> result = data.Where(p => ages.Contains(p.Age)).ToList();
Upvotes: 1