2

我有以下代码:

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 作为城市的项目(可以动态指定)

例子:

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

谢谢!

4

3 回答 3

1

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

var result = personList.GroupBy(x => x.City)
                       .Where ( g => g.Key == someCity || g.Key == anotherCity)
                       .Select( g => g.ToArray());
于 2011-09-30T21:31:57.627 回答
0

首先建立您要搜索的城市列表

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

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

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

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

于 2011-09-30T21:40:06.180 回答
0

下面的呢?如果您想让使用更整洁,您可以将其粘贴在扩展方法中。

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您选择的任何城市的人。

于 2011-09-30T21:45:14.160 回答