按条件将列表拆分为多个列表c#

时间:2017-04-11 05:35:47

标签: c#

我有一个由以下对象组成的列表

List<Person> PersonList

Person类

class Person
{
  public int PersonId{get;set;}
  public string PersonName{get;set;
  public int Age {get;set;}
}

我有另一个列表,其中包含我感兴趣的年龄列表,如12,14,16,24等。

List<int> AgeList

我想将PersonList的年龄与AgeList和找到的IF中的年龄进行比较,将其存储在基于每个组的单独列表中。例如,属于12岁的人应该在不同的列表中,年龄14在不同的列表中等等......

3 个答案:

答案 0 :(得分:1)

这是一些快速代码,没有LINQ。首先,您创建类型为Person的新列表,然后循环遍历您的人员列表,并为每个人检查年龄是否与您年龄列表中的年龄相同。

List<Person> finalList=new List<Person>();
foreach (var a in PersonList)
{
    foreach (var b in AgeList)
    {
        if (a.Age==b)
        {
            finalList.Add(a);
            break;
        }
    }
}

答案 1 :(得分:1)

List<Person> data = new List<Person>();
List<int> ages = new List<int>();
List<Person> result = data.Where(p => ages.Contains(p.Age)).ToList();

答案 2 :(得分:1)

LINQ解决方案:

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