Group by in LINQ
Załóżmy, że jeśli mamy klasę taką jak
class Person {
internal int PersonID;
internal string car ;
}
Teraz mam listę tej klasy: List<Person> persons;
Teraz ta lista może mieć wiele instancji z tymi samymi osobnikami, na przykład:
persons[0] = new Person { PersonID = 1, car = "Ferrari" };
persons[1] = new Person { PersonID = 1, car = "BMW" };
persons[2] = new Person { PersonID = 2, car = "Audi" };
Czy jest jakiś sposób, żebym mógł zebrać listę wszystkich samochodów, które ma?
Na przykład oczekiwany wynik to
class Result {
int PersonID;
List<string> cars;
}
Więc po zgrupowaniu dostałbym:
results[0].PersonID = 1;
List<string> cars = results[0].cars;
result[1].PersonID = 2;
List<string> cars = result[1].cars;
Z tego co dotychczas zrobiłem:
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key, // this is where I am not sure what to do
Czy ktoś mógłby mi wskazać w prawo kierunek? 7 answers
Absolutnie-w zasadzie chcesz:
var results = from p in persons
group p.car by p.PersonId into g
select new { PersonId = g.Key, Cars = g.ToList() };
Lub jako wyrażenie niezwiązane z zapytaniem:
var results = persons.GroupBy(
p => p.PersonId,
p => p.car,
(key, g) => new { PersonId = key, Cars = g.ToList() });
Zasadniczo zawartość grupy (w widoku jako IEnumerable<T>
) jest ciągiem wartości, które były w projekcji (p.car
w tym przypadku) obecne dla danego klucza.
Aby dowiedzieć się więcej o tym, jak działa GroupBy
, zapoznaj się z moim postem Edulinq w temacie.
Alternatywnie, ty można użyć Lookup
:
var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);
Można wtedy bardzo łatwo dostać samochody dla każdej osoby:
// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-26 16:16:48
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key,
/**/car = g.Select(g=>g.car).FirstOrDefault()/**/}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-24 16:56:41
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key, Cars = g.Select(m => m.car) };
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-19 09:51:02
Możesz też spróbować tego.
var results= persons.GroupBy(n => new { n.PersonId, n.car})
.Select(g => new {
g.Key.PersonId,
g.Key.car)}).ToList();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 06:43:04
Try
persons.GroupBy(x => x.PersonId).Select(x => x)
Lub
Aby sprawdzić, czy któraś z osób powtarza się na twojej liście, spróbuj
persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-25 10:13:29
Stworzyłem działający przykład kodu ze składnią zapytania i składnią metody. Mam nadzieję, że pomoże innym:)
Możesz również uruchomić kod na. Net Fiddle tutaj:
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public int PersonId;
public string car ;
}
class Result
{
public int PersonId;
public List<string> Cars;
}
public class Program
{
public static void Main()
{
List<Person> persons = new List<Person>()
{
new Person { PersonId = 1, car = "Ferrari" },
new Person { PersonId = 1, car = "BMW" },
new Person { PersonId = 2, car = "Audi"}
};
//With Query Syntax
List<Result> results1 = (
from p in persons
group p by p.PersonId into g
select new Result()
{
PersonId = g.Key,
Cars = g.Select(c => c.car).ToList()
}
).ToList();
foreach (Result item in results1)
{
Console.WriteLine(item.PersonId);
foreach(string car in item.Cars)
{
Console.WriteLine(car);
}
}
Console.WriteLine("-----------");
//Method Syntax
List<Result> results2 = persons
.GroupBy(p => p.PersonId,
(k, c) => new Result()
{
PersonId = k,
Cars = c.Select(cs => cs.car).ToList()
}
).ToList();
foreach (Result item in results2)
{
Console.WriteLine(item.PersonId);
foreach(string car in item.Cars)
{
Console.WriteLine(car);
}
}
}
}
Oto wynik:
1 Ferrari BMW 2 Audi ----------- 1 Ferrari BMW 2 Audi
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-30 19:27:00
Spróbuj tego:
var results= persons.GroupBy(n => n.PersonId)
.Select(g => new {
PersonId=g.Key,
Cars=g.Select(p=>p.car).ToList())}).ToList();
Ale pod względem wydajności następująca praktyka jest lepsza i bardziej zoptymalizowana pod kątem wykorzystania pamięci (gdy nasza tablica zawiera znacznie więcej elementów, takich jak miliony):
var carDic=new Dictionary<int,List<string>>();
for(int i=0;i<persons.length;i++)
{
var person=persons[i];
if(carDic.ContainsKey(person.PersonId))
{
carDic[person.PersonId].Add(person.car);
}
else
{
carDic[person.PersonId]=new List<string>(){person.car};
}
}
//returns the list of cars for PersonId 1
var carList=carDic[1];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-26 07:21:43