Linq投影问题

时间:2010-04-02 12:44:12

标签: 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";
   }
}

1 个答案:

答案 0 :(得分:4)

使用空合并运算符?如果左边的值?为null,它将替换右侧的值。

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子句之前选择感兴趣的字段以缩小带宽要求。