1

我需要按部门值对以下列表进行分组,但 LINQ 语法有问题。这是我的对象列表:

 var people = new List<Person>
 { 
    new Person { name = "John", department = new List<fields> {new fields { name = "department", value = "IT"}}}, 
    new Person { name = "Sally", department = new List<fields> {new fields { name = "department", value = "IT"}}},
    new Person { name = "Bob", department = new List<fields> {new fields { name = "department", value = "Finance"}}},
    new Person { name = "Wanda", department = new List<fields> {new fields { name = "department", value = "Finance"}}},
 };

我玩弄了分组。这是据我所知:

var query = from p in people
            from field in p.department
            where field.name == "department"
            group p by field.value into departments
            select new
            {
                Department = departments.Key,
                Name = departments
            };

因此可以遍历组,但不确定如何列出人员名称 -

foreach (var department in query)
{
    Console.WriteLine("Department: {0}", department.Department);
    foreach (var foo in department.Department)
    {
        // ??
    }
}

关于如何做得更好或如何列出相关部门的名称有什么想法吗?

4

3 回答 3

0

啊,应该是:

foreach (Person p in department.Name) Console.WriteLine(p.name);

谢谢你的眼睛,Fyodor!

于 2012-11-20T03:52:19.363 回答
0

您的department属性似乎是一个尴尬的实现,特别是如果您想按部门分组。使用 List 作为键进行分组会导致大量复杂性,而且这是不必要的,因为您只关心 List 中的一个元素。

另外,您似乎已经创建了fields该类作为模拟动态/匿名类型或仅模拟该类的一种方式Dictionary<string, string>,我真的不知道。我建议不要这样做;C# 已经内置了这些类型,解决它们只会效率低下,并且会阻止您使用 Intellisense。不管是什么导致你这样做,可能有一种更好、更 C# 风格的方法。此外——这是关键——你的代码看起来你可以忘记所有这些并制作department一个简单的字符串。

如果您可以控制数据结构,我建议重新组织它:

var people = new List<Person> { 
    new Person { name = "John", department = "IT"}, 
    new Person { name = "Sally", department = "IT"},
    new Person { name = "Bob", department = "Finance"},
    new Person { name = "Wanda", department = "Finance"},
};

突然之间,将所有内容分组变得简单:

var departments = from p in people
                  group p by p.department into dept
                  select dept;

foreach (var dept in departments)
{
    Console.WriteLine("Department: {0}", dept.Key);
    foreach (var person in dept)
    {
        Console.WriteLine("Person: {0}", person.name);
    }
}

如果你必须保持数据结构不变,你可以试试这个:

from p in people
from field in p.department
where field.name equals "department"
group p by field.value into dept
select dept;

这应该适用于上述嵌套循环。

于 2012-11-20T03:42:08.950 回答
0

每个部门的人员列表可以通过 访问department.Name。简单地迭代它:

    foreach( var person in department.Name ) Console.WriteLine( person.name );

department.Department另一方面,的值属于 类型string。此值来自departments.Key,而后者又来自field.value- 因为这是您分组的关键。

foreach 语句department.Department仍然编译得很好,因为string实现了IEnumerable<char>. 因此,您的foo变量的类型为char.

于 2012-11-20T03:35:30.417 回答