从集合中返回一些空值

时间:2015-10-24 21:25:14

标签: c# linq null

我有一个LINQ查询,我需要返回数据库中的所有客户,但并非所有客户都有中间名。这是我的问题:

select new 
{
        firstName = a.firstname,
        middleName = a.middlename,
        lastName = a.lastname,
};
foreach(var c in queryAccount) 
{    
    console.writeline(c.firstname);
    console.writeline(c.middlename);
    console.writeline(c.lastname);
}

我正在寻找的东西类似于:

if (c.middlename != null)
{
    console.writeline(c.middlename);
}

有谁知道我怎么能让它发挥作用?

2 个答案:

答案 0 :(得分:2)

您只需使用Null Colaescing运算符: -

select new {
        firstName = a.firstname,
        middleName = a.middlename ?? String.Empty,
        lastName = a.lastname,
};

答案 1 :(得分:0)

Rahul的回答是正确的。此外,如果你不想分配'middleName',你可以这样做:

Select(x =>
            {
                var obj = new TestData
                {
                    Lastname = x.Lastname,
                    Firstname = x.Firstname
                };
                if (!string.IsNullOrEmpty(x.Middlename))
                    obj.Middlename = x.Middlename;
                return obj;
            });