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);
精彩评论