内选择LINQ选择 [英] LINQ Select within a Select

查看:184
本文介绍了内选择LINQ选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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




  • 名称

  • ManagerName



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



现在,这里是我遇到的问题。当我做了选择中的选择的值 ManagerName 字段,它的每个对象返回的:



<预类=郎无prettyprint-覆盖> System.Data.Common.Internal .Materialization.CompensatingCollection<串GT;

下面的查询:



<预类=郎-CS prettyprint-覆盖> VAR的查询=从E在db.Employees

选择新的
{
名称= e.Name,
在db.Employees
从EM2 ManagerName =
,其中(em2.EmployeeID == e.ManagerID)
选择em2.Name
};



具体而言,当我在看的价值 ManagerName ,我看到它是产生单个项目的枚举。而且该单个项目是包含管理器的名称的字符串。所以,我觉得我很接近



问:我怎样才能改变我的查询,以便它返回的对象,其中每个枚举对象只是有两个字符串字段,名称 ManagerName


解决方案

试试这个:

  VAR的查询=从E在db.Employees 
选择新的
{
名称= e.Name,
ManagerName = db.Employees
。凡(X => x.EmployeeID == e.ManagerID)
。选择(X => x.Name).SingleOrDefault()
};



然而,如果你使用正确的 EF (我假设你正在使用),你应该有你可以使用导航属性:

  VAR的查询=从E在db.Employees 
选择新的
{
名称= e.Name,
ManagerName = e.Manager.Name
};


I am trying to query a collection that contains Employee information. 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 select within a select, the value of the ManagerName field that is returned on each object is:

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.

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

解决方案

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:

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

这篇关于内选择LINQ选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆