按属性分类的正确方法

时间:2014-01-16 09:43:31

标签: c# linq

我做了一个C#LINQ查询,按属性对(或组)进行分类,我几乎可以肯定有更好的方法。我的项目充满了这些查询,所以我对如何以正确的方式实现这一点非常感兴趣。

这是我的查询的样子:

var g = _repository.GetEmployees();
var result = 
    g.GroupBy(x => x.City, (key, group) => group.First())
    .Select(x => new { 
        city = x.City,
        employees = g
            .Where(y=>y.EmployeeID == x.EmployeeID)
            .Select(y=> new {
                fullname = y.FirstName + " " + y.LastName,
                title = y.Title
            })
            .OrderBy(y=>y.fullname)
    })
    .OrderBy(x => x.city);

JSON输出示例:

[
    {
        "city":"Barcelona",
        "employees":[
            {
                "fullname":"Foo Bar",
                "title":"Help Desk Technician"
            },
            {
                "fullname":"Lorem Ipsum",
                "title":"Information Technology Director"
            }
        ]
    },
    {
        "city":"London",
        "employees":[
            {
                "fullname":"Le Query",
                "title":"Information Technology Manager"
            },
            {
                "fullname":"Please Help",
                "title":"Management Information Systems Director"
            }
        ]
    }
]

结果很好。实现它的最佳方法是什么?

1 个答案:

答案 0 :(得分:5)

听起来你只是想要:

var result = g.GroupBy(x => x.City, (key, group) => new {
                           city = key,
                           employees = group.Select(emp => new {
                               fullname = emp.FirstName + " " + emp.LastName,
                               title = emp.Title
                           })
                       });

换句话说,你只是为每个群体提供一个投影,这是“与城市的匿名类型,以及该城市的所有员工”。