简体   繁体   中英

Split List into Multiple Lists by Criteria c#

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

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;
        }
    }
}
List<Person> data = new List<Person>();
List<int> ages = new List<int>();
List<Person> result = data.Where(p => ages.Contains(p.Age)).ToList();

LINQ解决方案:

List<Person> personAgeList = PersonList.Where(p => AgeList.Contains(p.Age)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM