Concat items in linq
I have the following code:
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 Per开发者_如何学Goson("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"));
So then I want to group the list by Cities, and I do the following;
var result = personList.GroupBy(x => x.City);
But now what I want to do is to concatenate the items that have 1 or 3 as a City (it can be specified dynamically)
Example:
The first item on result would return an array of persons that contain cities 1, 3
Thanks!
You can just use a Where()
filter and project each remaining group into an array using ToArray()
:
var result = personList.GroupBy(x => x.City)
.Where ( g => g.Key == someCity || g.Key == anotherCity)
.Select( g => g.ToArray());
First build your list of cities that you want to search against
List<int> citesToFind = new List<int>();
// add 1, 3, etc to this list (can be generated dyamically)
Then use .Contains()
in your LINQ:
var result = from person in personList
where citiesToFind.Contains(person.City)
select person;
Of course you can add whatever other grouping or filtering you want, but using .Contains()
is I think the essential part you're missing.
How about the following? You could stick it in an extension method if you want to make the usage neater.
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};
}
}
You can then query the personDictionary
for the people from any city of your choosing.
精彩评论