gpt4 book ai didi

c# - 如何在 Linq 中对组内的元素进行分组

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:32 28 4
gpt4 key购买 nike

我有一个 Employee 集合,我想以这样一种方式进行过滤,即只应过滤前两列,并应附加第三列值,最终结果应在一行中

下面是我的代码

List<Employe> Employeecollection = new List<Employe>();

Employeecollection.Add(new Employe("Employee1", "Dept1","Language1"));
Employeecollection.Add(new Employe("Employee2", "Dept2", "Language2"));
Employeecollection.Add(new Employe("Employee3", "Dept3", "Language3"));
Employeecollection.Add(new Employe("Employee3", "Dept3", "Language3"));
Employeecollection.Add(new Employe("Employee1", "Dept1", "Language2"));

foreach (Employe item in Employeecollection.GroupBy(x => new { fName = x.EmpName, lName = x.EmpDept, mName = x.KnownLanguages }).Select(g => g.First()))
{
Console.WriteLine(item.EmpName + " " + item.EmpDept + " " + item.KnownLanguages);
}

但我想显示如下结果

Employee1 Dept1 Language1,Language2Employee2 Dept2 Language2Employee3 Dept3 Language3

最佳答案

按姓名和部门对员工进行分组,然后为每个员工选择连接的已知语言字符串:

from e in Employeecollection
group e by new { e.Name, e.EmpDept } into g
select new {
g.Key.Name,
g.Key.EmpDept,
Languages = String.Join(",", g.Select(x => x.KnownLanguages))
}

如果您希望结果为单行,则改为执行以下投影:

select String.Format("{0} {1} {2}", 
g.Key.Name, g.Key.EmpDept, String.Join(",", g.Select(x => x.KnownLanguages)))

顺便说一句,我认为它是一个奇怪的属性名称KnownLanguages,用于包含单一语言的属性

关于c# - 如何在 Linq 中对组内的元素进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17303311/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com