1

我有一个员工集合,我想以这样一种方式进行过滤,即仅应过滤前 2 列,并应附加第三列值,最终结果应位于单行中

以下是我的代码

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

但我想显示如下结果

员工 1 部门 1 语言 1、语言 2
员工 2 部门 2 语言 2
员工 3 部门 3 语言 3
4

2 回答 2

5

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

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顺便说一句,我认为对于拥有单一语言的属性来说,这是一个奇怪的属性名称

于 2013-06-25T17:05:29.630 回答
2

你不想在KnownLanguages. 它不应该包含在您的组选择器中。组选择器应该为组中的所有项目选择您希望相同的所有内容。

您还需要更改打印结果的方式。通过 获取组中每个项目的公共值Key,并通过迭代组本身获取其他值。

var query = Employeecollection.GroupBy(x => new
{
    x.EmpName,
    x.EmpDept
};

foreach (var group in query)
{
    string languages = string.Join(", ", 
        group.Select(employee => employee.KnownLanguages)
        .Distinct());
    Console.WriteLine(group.Key.EmpName + "   " + group.Key.EmpDept + " " 
        + languages;
}
于 2013-06-25T17:07:45.890 回答