开发者

Linq orderby on multiple columns with one potentially null

开发者 https://www.devze.com 2023-03-06 05:27 出处:网络
I have a table with 2 fields in it: [Name] and [Order] [Order] can be null Using LINQ, I\'d like to be able to order by [Order] or if [Order] is null then order by [Name]

I have a table with 2 fields in it: [Name] and [Order]

[Order] can be null

Using LINQ, I'd like to be able to order by [Order] or if [Order] is null then order by [Name]

here is my non-working code:

from ft in FacetTypes
orderby ft.Name, ft.Order ascending   
select ft

Is this possible in linq?

EDIT:

[Order] is int? [Name] is string

The query is an Entity Framework 4 one.

ANSWER:

This is what I eventually got to work.

ft.Order == null ? f开发者_JAVA技巧t.Name : SqlFunctions.StringConvert((double)ft.Order)


Do you mean if Order is null for a single element, use Name instead? If so, I think you want:

from ft in FacetTypes
orderby ft.Order ?? ft.Name
select ft;

This is just using the null-coalescing operator introduced in C# 2.


How about this:

var resultSet = 
     ft.Order == null ? 
          FacetTypes.OrderBy(item => item.Name) : 
          FacetTypes.OrderBy(item => item.Order);
0

精彩评论

暂无评论...
验证码 换一张
取 消