在linq中连接项

本文关键字:连接 linq | 更新日期: 2023-09-27 18:10:22

我有以下代码:

class Person
{
    public String Name { get; set; }
    public String LastName { get; set; }
    public String City { get; set; }
    public Person(String name, String lastName, String city)
    {
        Name = name;
        LastName = lastName;
        City = city;
    }
}
...
personList.Add(new Person("a", "b", "1"));
personList.Add(new Person("c", "d", "1"));
personList.Add(new Person("e", "f", "2"));
personList.Add(new Person("g", "h", "1"));
personList.Add(new Person("i", "j", "2"));
personList.Add(new Person("k", "l", "1"));
personList.Add(new Person("m", "n", "3"));
personList.Add(new Person("o", "p", "3"));
personList.Add(new Person("q", "r", "4"));
personList.Add(new Person("s", "t", "5"));

然后我想按城市对列表进行分组,我做了下面的操作;

var result = personList.GroupBy(x => x.City);

现在我要做的是将包含1或3的项目连接为City(可以动态指定)

的例子:

结果的第一项将返回包含城市1,3的人员数组

谢谢!

在linq中连接项

您可以使用Where()过滤器并使用ToArray()将每个剩余组投影到数组中:

var result = personList.GroupBy(x => x.City)
                       .Where ( g => g.Key == someCity || g.Key == anotherCity)
                       .Select( g => g.ToArray());

首先创建要搜索的城市列表

List<int> citesToFind = new List<int>();
// add 1, 3, etc to this list (can be generated dyamically)

然后在LINQ中使用.Contains():

var result = from person in personList
             where citiesToFind.Contains(person.City)
             select person;

当然,您可以添加任何其他分组或过滤您想要的,但使用.Contains()是我认为您错过的重要部分。

以下内容如何?如果你想让用法更简洁,你可以把它放在一个扩展方法中。

var personDictionary = new Dictionary<string, List<Person>>();
foreach(var person in personList)
{
  if (personDictionary.HasKey(person.City)
  {
    personDictionary[person.City].Add(person);
  }
  else
  {
    personDictionary[person.City] = new List<Person>{person};
  }
}

然后您可以查询personDictionary中您选择的任何城市的人。