c# - Linq投影问题

标签 c# linq linq-to-sql projection

我正在尝试执行以下操作:

from c in db.GetAllContactsQuery()
select new
{
   ID= c.ID,
   LastName = c.LastName,
   FirstName = c.FirstName,
   Email = c.Email,
   City =c.City+" "+c.State
}

我遇到的问题是,如果 c.City 或 c.State 为 null,则 City 属性返回 null。如何在 City= 声明旁边放置一个函数?

我真的很想知道是否可以做这样的事情(这行不通):

from c in db.GetAllContactsQuery()
select new
{
   ID= c.ID,
   LastName = c.LastName,
   FirstName = c.FirstName,
   Email = c.Email,
   City ={ c=>
         //completely sweet function in here
         if(String.IsNullOrEmpty(c.City))
                return "booyah";
   }
}

最佳答案

使用空合并运算符?如果 ?? 左边的值为空,则用右边的值代替。

from c in db.GetAllContactsQuery()
select new
{
   ID= c.ID,
   LastName = c.LastName,
   FirstName = c.FirstName,
   Email = c.Email,
   City =(c.City??"")+" "+(c.State??"")
}

在回答您的评论时,您需要使用 AsEnumerable 以便您可以充分利用 CLR 优点:

db.GetAllContactsQuery()
    .AsEnumerable()
    .Select(c=>new
        {
           ID= c.ID,
           LastName = c.LastName,
           FirstName = c.FirstName,
           Email = c.Email,
           City =MyClrMethod(c.City,c.State)
        })

如果 db.GetAllContactsQuery() 返回许多附加字段,请在 AsEnumerable 子句之前选择感兴趣的字段以缩小带宽要求。

关于c# - Linq投影问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2566678/

相关文章:

c# - []、get_Item() 和 Item[] 之间的 Excel Interop 区别

c# - 从字符串映射枚举

ASP.NET LINQ to SQL SubmitChanges() 不更新数据库

Linq-to-Sql 计数

c# - 将 Linq-to-SQL 类映射到具有嵌套集合的域类

c# - 使用 string,string, string,int 和 string,object 创建一个字典

c# - 泛型基类的派生类型

c# - 在 C++ 中是否有与 LINQ 相对于数据表的等价物?

c# - foreach 上的 if 语句

c# - 如何使用 C# 获取父类别? (包括点网 fiddle )