LINQ Select distinct from a List?
I have the following list:
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"));
How do I retrieve a list of persons differing from the city name?
Expecting Results:
An Array/Collection of lists (persons) differing from the city name:
result[0] = List<Person> where city name = "1"
re开发者_StackOverflowsult[1] = List<Person> where city name = "2"
result[n] = List<Person> where city name = "whatever"
You could use LINQ to group the persons list by city:
var groupedPersons = personList.GroupBy(x => x.City);
foreach (var g in groupedPersons)
{
string city = g.Key;
Console.WriteLine(city);
foreach (var person in g)
{
Console.WriteLine("{0} {1}", person.Name, person.LastName);
}
}
In addition to Darin Dimitrov's answer, here is the same in query syntax:
var groupByCityQuery = from person in personList
group person by person.City into grouping
select grouping;
Judging by this comment: No, I wan't a list containing all the Persons that contains 1 as a city and another that contains 2 as a city...
We can do something like this:
var city1People = personList.Where(x => x.city == "1").ToList();
var city2People = personList.Where(x => x.city == "2").ToList();
if this is something more dynamic, like you're going to have N cities and want an individual list of people per city, you're going to need to return a collection of lists.
精彩评论