C# 选择中的 LINQ 选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17841108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:38:44  来源:igfitidea点击:

LINQ Select within a Select

c#linq

提问by DK ALT

I am trying to query a collection that contains Employeeinformation. When I query that collection I would like to return an enumeration of objects where each object has two fields:

我正在尝试查询包含员工信息的集合。当我查询该集合时,我想返回一个对象枚举,其中每个对象都有两个字段:

  • Name
  • ManagerName
  • 姓名
  • 经理姓名

(Note that every Manager is also an Employee!)

(请注意,每个经理也是员工!)

Now, here's the problem I am having. When I do a selectwithin a select, the value of the ManagerNamefield that is returned on each object is:

现在,这就是我遇到的问题。当我在 aselect中执行 a 时selectManagerName每个对象上返回的字段的值是:

System.Data.Common.Internal.Materialization.CompensatingCollection<string>

Here's the query:

这是查询:

var query =
    from e in db.Employees    
    select new
    {
        Name = e.Name,
        ManagerName =
            from em2 in db.Employees
            where (em2.EmployeeID == e.ManagerID)
            select em2.Name
    };

Specifically, when I look at the value of ManagerName, I see that it is an enumeration that yields a single item. And that the single item is a string that contains the name of the Manager. So, I think I'm close.

具体来说,当我查看 的值时ManagerName,我看到它是一个生成单个项目的枚举。并且单个项目是一个包含经理姓名的字符串。所以,我想我很接近了。

Question:How can I change my query so that instead it returns an enumeration of objects where each object simply has two string fields, Nameand ManagerName?

问题:如何更改我的查询,以便它返回对象的枚举,其中每个对象只有两个字符串字段,NameManagerName?

采纳答案by Daniel Hilgarth

Try this:

尝试这个:

var query = from e in db.Employees
            select new
            {
                Name = e.Name,
                ManagerName = db.Employees
                                .Where(x => x.EmployeeID == e.ManagerID)
                                .Select(x => x.Name).SingleOrDefault()
            };

However, if you correctly mapped your database with EF(which I suppose you are using), you should have a navigation property you can utilize:

但是,如果您使用EF(我想您正在使用)正确映射了您的数据库,您应该有一个可以使用的导航属性:

var query = from e in db.Employees
            select new
            {
                Name = e.Name,
                ManagerName = e.Manager.Name
            };

回答by D Stanley

Looks like a self-join should work:

看起来自连接应该可以工作:

var query = from e in db.Employees
            join m in db.Employees on e.ManagerID equals m.EmployeeID
              select new
              {
                Name = e.Name,
                ManagerName = m.Name
              };