Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# linq中的Concat项目_C#_Linq_Concat - Fatal编程技术网

C# linq中的Concat项目

C# linq中的Concat项目,c#,linq,concat,C#,Linq,Concat,我有以下代码: 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 = last

我有以下代码:

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的人员数组


谢谢

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


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

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

当然,您可以添加任何其他您想要的分组或筛选,但是使用
.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};
  }
}
var personDictionary=newdictionary();
foreach(个人列表中的var人员)
{
if(personDictionary.HasKey(person.City)
{
personDictionary[个人.城市].添加(个人);
}
其他的
{
personDictionary[person.City]=新列表{person};
}
}

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

您可以指定“连接”的条件吗项目。你清楚地知道如何在LINQ中分组,我相信你会自己找到Where子句。只是想更多地理解你的问题。如果LINQ不是问题的一部分,这可能会很有用。
var result = from person in personList
             where citiesToFind.Contains(person.City)
             select person;
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};
  }
}