当我在我的orderby中使用两个可空属性时,是否需要nullcheck?

时间:2013-11-21 12:08:23

标签: c# linq

我有一个包含两个属性的列表,Lastname和Firstname。它们可以为空,应该是。

这是我的代码行:

return memberlist.OrderBy(x => x.LastName).ThenBy(x => x.Firstname);

我的问题是,如果Lastname为null,它将运行ThenBy()而Else我需要创建一个nullcheck吗?我想确保它按姓氏排序,如果是null,则按名字命令。

假设我有一个如下所示的列表:

var data = new List<Member>
{
    new Member { FirstName = "null", LastName = "A" },
    new Member { FirstName = "B", LastName = null },
    new Member { FirstName = "A", LastName = null },
    new Member { FirstName = null , LastName = "B" },
    new Member { FirstName = "A" , LastName = "B" },
    new Member { FirstName = "B" , LastName = "A" },
};

我希望输出如下:

A
A
A
B
B
B

var result = data.OrderBy(x => x.LastName).ThenBy(x => x.FirstName);

1 个答案:

答案 0 :(得分:1)

是的,它会运行ThenBy()

基本上,具有null LastName属性的所有项目将由FirstName然后排序。

OrderBy()会将null值放在非空值之前。

在以下示例中,result按照声明的顺序返回项目:

var data = new List<Member>
{
    new Member { FirstName = "A", LastName = null },
    new Member { FirstName = "B", LastName = null },
    new Member { FirstName = "A", LastName = "NotNull" },
    new Member { FirstName = "B", LastName = "NotNull" }
};

var result = data.OrderBy(x => x.LastName).ThenBy(x => x.FirstName);

修改

根据以下评论和问题更新,您可以使用以下内容在OrderBy()FirstName的逻辑组合上执行LastName

var result = data.OrderBy(x => string.IsNullOrWhiteSpace(x.LastName) ? x.FirstName : x.LastName)
                 .ThenBy(x => x.FirstName)