假设我们有这样一个类:

class Person { 
    internal int PersonID; 
    internal string car; 
}

我有一个这个类的列表:list <Person> persons;

这个列表可以有多个具有相同personid的实例,例如:

persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 

有没有办法我可以通过PersonID分组,并获得他所有的汽车列表?

例如,预期的结果将是

class Result { 
   int PersonID;
   List<string> cars; 
}

分组之后,我得到:

results[0].PersonID = 1; 
List<string> cars = results[0].cars; 

result[1].PersonID = 2; 
List<string> cars = result[1].cars;

从我目前所做的来看:

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

有人能告诉我正确的方向吗?


当前回答

try

persons.GroupBy(x => x.PersonId).Select(x => x)

or

检查是否有人在你的列表中重复出现

persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)

其他回答

你也可以试试这个:

var results= persons.GroupBy(n => new { n.PersonId, n.car})
                .Select(g => new {
                               g.Key.PersonId,
                               g.Key.car)}).ToList();

我想给出一个在c#中使用GroupBy的复杂查询的例子

    var records= (from x in db.Table
                        select new
                        {
                            x.Id,
                            x.ProgramId,
                            ProgramName = x.Program.Name,
                            Version= x.Program.Version,
                            x.Date,
                            x.Maks
                        });
    // I take two date(openDate and closeDate)
    var try= records
        .Where(x => x.Date>= openDate && x.Date<= closeDate)
        .GroupBy(x => new
        {
            x.ProgramId,
            MonthYear=x.Date.Value.Month + "-" + x.Date.Value.Year,
                
        })
        .Select(x => new
        {                  
           ProgramName = x.Select(y => y.ProgramName).FirstOrDefault(),
           Version= x.Select(y => y.Version).FirstOrDefault(),
           x.Key.MonthYear,
           x.Maks.Max()
          })
        .ToList();
    datagridview1.DataSource = try;

另一种方法可以选择不同的PersonId和组与人连接:

var result = 
    from id in persons.Select(x => x.PersonId).Distinct()
    join p2 in persons on id equals p2.PersonId into gr // apply group join here
    select new 
    {
        PersonId = id,
        Cars = gr.Select(x => x.Car).ToList(),
    };

或者与流畅的API语法相同:

var result = persons.Select(x => x.PersonId).Distinct()
    .GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
    {
        PersonId = id,
        Cars = gr.Select(x => x.Car).ToList(),
    });

GroupJoin在第一个列表(在本例中是PersonId列表)中生成一个条目列表,每个条目在第二个列表(人员列表)中生成一组已连接的条目。

我已经用查询语法和方法语法创建了一个工作代码示例。我希望这能帮助到其他人:)

你也可以在。net Fiddle上运行代码:

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);
            }
        }
    }
}

结果如下:

1
Ferrari
BMW
2
Audi
-----------
1
Ferrari
BMW
2
Audi

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()/**/}