LINQ Choose different from the 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 to get a list of people different from the name of the city?

Expected Results:

Array / Collection of lists (of persons) that differ from the name of the city:

result[0] = List<Person> where city name = "1"
result[1] = List<Person> where city name = "2"
result[n] = List<Person> where city name = "whatever"
+5
source share
3 answers

You can use LINQ to group the list of people 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);
    }
}
+8
source

In addition to Darin Dimitrov’s answer, the query syntax is one and the same:

var groupByCityQuery = from person in personList 
                       group person by person.City into grouping 
                       select grouping;
+3
source

: , , , 1 , , 2 ...

- :

var city1People = personList.Where(x => x.city == "1").ToList();
var city2People = personList.Where(x => x.city == "2").ToList();

- , , N , .

+1

All Articles