【问题标题】:Group by in LINQ with 2 attributes在 LINQ 中按 2 个属性分组
【发布时间】:2017-11-17 07:01:29
【问题描述】:

这是一个已经提出的问题,但that question 仅使用 2 个属性,我需要使用 3 个属性,所以我复制粘贴了大部分文本。

假设我们有一个类似的类

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

现在我有一个这个类的列表:列出人员;

现在这个列表可以有多个相同的 PersonID 实例,例如。

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

有没有办法可以按 PersonID 分组并获取他拥有的所有汽车和朋友的列表?例如,预期的结果是:

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

从我目前所做的:

IEnumerable resultsForDisplay = ResultFromSQL_Query.GroupBy(
    p => p.PersonId.ToString(),
    p => p.car,
    (key,  g) => new { PersonId = key, car = g.ToList()});

但现在我无法在 resultsForDisplay 中获取 friend's 数组

【问题讨论】:

    标签: c# linq group-by


    【解决方案1】:

    当然,您也可以对组 g 执行 LINQ 查询,例如:

    IEnumerable<Result> resultsForDisplay = from q in ResultFromSQL_Query
        group q by q.PersonID into g
        select new Result {PersonID = g.Key,cars = g.Select(x => x.car).ToList(), friends = g.Select(x => x.friend).ToList()};

    或者用 lambda 表达式

    IEnumerable<Result> results = persons.GroupBy(x => x.PersonID)
        .Select(g => new Result { PersonID = g.Key, cars = g.Select(x => x.car).ToList(), friends = g.Select(x => x.friend).ToList()};

    因此,您可以对组执行任何 LINQ 查询(因此在该组的元素上表现为IEnumerable&lt;&gt;),例如.Select(..),也可以是.Sum(..).Average(..) 和其他子查询聚合

    【讨论】:

    • 嗨,请原谅我,但我是 Linq 和 Lambda 表达式的新手。能否请您将此语法转换为 lambda 表达式?
    • 另外,当我尝试使用您的语法时,它在 Resultselect new Result { 上给我一个错误,错误显示 The type or namespace name 'Result' could not be found (are you missing a using directive or an assembly reference?)
    • @AtifWaqar:是的,我认为这些必须写在一行上。
    • @AtifWaqar:Result 是您问题中的一个类。如果您没有正确引用它,那么只有您可以回答为什么会这样。您是否缺少 using 指令?还是您只是没有将类放在代码中而只是放在问题中?
    • @WillemVanOnsem 这太棒了。我被困在这个问题上很长时间了。非常感谢您的解决方案:) 关于Result,我知道了,它是返回数据类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多