如何在查询中设置默认空

时间:2012-06-21 12:49:23

标签: asp.net-mvc-3 linq linq-to-sql

所以我有这个查询:

   var list = (from x in xList 
                 join a in AList on x.commonfield equals a.commonfield
                 join b in BList on x.newCommonField equals b.newCommonField
                 from c in Clist.Where(p=>p.connectorID==x.connectorID).DefaultifEmpty()
                                select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB,c.name}).ToList();

    list.ForEach(el =>
                    {
                        el.x.DesiredFieldFromA= el.DesiredFieldFromA;
                        el.x.DesiredFieldFromB= el.DesiredFieldFromB ;
                        el.x.Name=el.name;
                    });
    return list.Select(p=>p.x);

当我这样做时:

select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB,c.name}).ToList();

问题#1:我怎么能告诉它它仍然应该显示记录...但是如果name字段为null则输入string.empty。
一些事情:

select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB,c.name??string.Empty}).ToList();

问题2:我怎么能告诉它即使“connectorID”为空...我仍然需要它来显示x记录
提前致谢!

#1和#2的解决方案如下:

from c in Clist.Where(p=>p.connectorID==x.connectorID).DefaultifEmpty()
                                select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB,name= (c==null) ?"Not Defined": c.name}).ToList();

2 个答案:

答案 0 :(得分:1)

对于问题#2,请更改:

from c in Clist.Where(p=>p.connectorID==x.connectorID).DefaultidEmpty()

为:

from c in Clist.Where(p=>p.connectorID==x.connectorID || x.connectorID == null)

答案 1 :(得分:0)

问题#1,试试这个:

select new { 
    x, 
    a.DesiredFieldFromA, 
    b.DesiredFieldFromB, 
    name = c.name ?? string.Empty
}).ToList();

您需要指定名称“name”,以便您可以使用表达式进行分配。

对于问题#2,请参阅jonnyGold's answer