LINQ order by null column where order is ascending and nulls should be last
I'm trying to sort a list of products by their price.
The result set needs to list products by price from low to high by the column LowestPrice
. However, this column is nullable.
I can sort the list in descending order like so:
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
// returns: 102, 101, 100, null, null
However I can't figure out how to sort this in ascending order.
// i'd like: 100, 101, 102, null, null
c# linq sorting
add a comment |
I'm trying to sort a list of products by their price.
The result set needs to list products by price from low to high by the column LowestPrice
. However, this column is nullable.
I can sort the list in descending order like so:
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
// returns: 102, 101, 100, null, null
However I can't figure out how to sort this in ascending order.
// i'd like: 100, 101, 102, null, null
c# linq sorting
6
orderby p.LowestPrice ?? Int.MaxValue;
is a simple way.
– PostMan
Jun 23 '11 at 22:44
2
@PostMan: Yes, it's simple, it achieves the right result, butOrderByDescending, ThenBy
is clearer.
– jason
Jun 23 '11 at 23:30
@Jason, yeah I didn't know the syntax for theorderby
, and got side tracked looking for it :)
– PostMan
Jun 24 '11 at 1:37
add a comment |
I'm trying to sort a list of products by their price.
The result set needs to list products by price from low to high by the column LowestPrice
. However, this column is nullable.
I can sort the list in descending order like so:
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
// returns: 102, 101, 100, null, null
However I can't figure out how to sort this in ascending order.
// i'd like: 100, 101, 102, null, null
c# linq sorting
I'm trying to sort a list of products by their price.
The result set needs to list products by price from low to high by the column LowestPrice
. However, this column is nullable.
I can sort the list in descending order like so:
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
// returns: 102, 101, 100, null, null
However I can't figure out how to sort this in ascending order.
// i'd like: 100, 101, 102, null, null
c# linq sorting
c# linq sorting
edited Oct 3 '14 at 21:37
JasonMArcher
9,333104849
9,333104849
asked Jun 23 '11 at 22:42
sf.sf.
9,03594055
9,03594055
6
orderby p.LowestPrice ?? Int.MaxValue;
is a simple way.
– PostMan
Jun 23 '11 at 22:44
2
@PostMan: Yes, it's simple, it achieves the right result, butOrderByDescending, ThenBy
is clearer.
– jason
Jun 23 '11 at 23:30
@Jason, yeah I didn't know the syntax for theorderby
, and got side tracked looking for it :)
– PostMan
Jun 24 '11 at 1:37
add a comment |
6
orderby p.LowestPrice ?? Int.MaxValue;
is a simple way.
– PostMan
Jun 23 '11 at 22:44
2
@PostMan: Yes, it's simple, it achieves the right result, butOrderByDescending, ThenBy
is clearer.
– jason
Jun 23 '11 at 23:30
@Jason, yeah I didn't know the syntax for theorderby
, and got side tracked looking for it :)
– PostMan
Jun 24 '11 at 1:37
6
6
orderby p.LowestPrice ?? Int.MaxValue;
is a simple way.– PostMan
Jun 23 '11 at 22:44
orderby p.LowestPrice ?? Int.MaxValue;
is a simple way.– PostMan
Jun 23 '11 at 22:44
2
2
@PostMan: Yes, it's simple, it achieves the right result, but
OrderByDescending, ThenBy
is clearer.– jason
Jun 23 '11 at 23:30
@PostMan: Yes, it's simple, it achieves the right result, but
OrderByDescending, ThenBy
is clearer.– jason
Jun 23 '11 at 23:30
@Jason, yeah I didn't know the syntax for the
orderby
, and got side tracked looking for it :)– PostMan
Jun 24 '11 at 1:37
@Jason, yeah I didn't know the syntax for the
orderby
, and got side tracked looking for it :)– PostMan
Jun 24 '11 at 1:37
add a comment |
8 Answers
8
active
oldest
votes
Try putting both columns in the same orderby.
orderby p.LowestPrice.HasValue descending, p.LowestPrice
Otherwise each orderby is a separate operation on the collection re-ordering it each time.
This should order the ones with a with a value first, "then" the order of the value.
5
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
16
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
This Worked to order fields with values on top and null fields on bottom i used this :orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.
– stom
Sep 27 '15 at 11:32
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
add a comment |
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
4
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
add a comment |
I have another option in this situation.
My list is objList, and I have to order but nulls must be in the end.
my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
add a comment |
The solution for string values is really weird:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
The only reason that works is because the first expression, OrderBy()
, sort bool
values: true
/false
. false
result go first follow by the true
result (nullables) and ThenBy()
sort the non-null values alphabetically.
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);
1
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
add a comment |
my decision:
Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)
add a comment |
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
add a comment |
I was trying to find a LINQ solution to this but couldn't work it out from the answers here.
My final answer was:
.OrderByDescending(p => p.LowestPrice.HasValue).ThenBy(p => p.LowestPrice)
add a comment |
Below is extension method to check for null if you want to sort on child property of a keySelector.
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}
And simple use it like:
var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6461479%2flinq-order-by-null-column-where-order-is-ascending-and-nulls-should-be-last%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try putting both columns in the same orderby.
orderby p.LowestPrice.HasValue descending, p.LowestPrice
Otherwise each orderby is a separate operation on the collection re-ordering it each time.
This should order the ones with a with a value first, "then" the order of the value.
5
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
16
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
This Worked to order fields with values on top and null fields on bottom i used this :orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.
– stom
Sep 27 '15 at 11:32
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
add a comment |
Try putting both columns in the same orderby.
orderby p.LowestPrice.HasValue descending, p.LowestPrice
Otherwise each orderby is a separate operation on the collection re-ordering it each time.
This should order the ones with a with a value first, "then" the order of the value.
5
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
16
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
This Worked to order fields with values on top and null fields on bottom i used this :orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.
– stom
Sep 27 '15 at 11:32
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
add a comment |
Try putting both columns in the same orderby.
orderby p.LowestPrice.HasValue descending, p.LowestPrice
Otherwise each orderby is a separate operation on the collection re-ordering it each time.
This should order the ones with a with a value first, "then" the order of the value.
Try putting both columns in the same orderby.
orderby p.LowestPrice.HasValue descending, p.LowestPrice
Otherwise each orderby is a separate operation on the collection re-ordering it each time.
This should order the ones with a with a value first, "then" the order of the value.
answered Jun 23 '11 at 22:47
DaveShawDaveShaw
40.6k1090124
40.6k1090124
5
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
16
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
This Worked to order fields with values on top and null fields on bottom i used this :orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.
– stom
Sep 27 '15 at 11:32
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
add a comment |
5
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
16
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
This Worked to order fields with values on top and null fields on bottom i used this :orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.
– stom
Sep 27 '15 at 11:32
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
5
5
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
cheers. so simple, i feel like an idiot :P
– sf.
Jun 23 '11 at 22:50
16
16
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
Common mistake, people do the same with Lamda Syntax - using .OrderBy twice instead of .ThenBy.
– DaveShaw
Jun 23 '11 at 22:51
This Worked to order fields with values on top and null fields on bottom i used this :
orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.– stom
Sep 27 '15 at 11:32
This Worked to order fields with values on top and null fields on bottom i used this :
orderby p.LowestPrice == null, p.LowestPrice ascending
Hope helps someone.– stom
Sep 27 '15 at 11:32
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
@DaveShaw thank you for the tip - especially the comment one - very tidy - love it
– Demetris Leptos
Dec 3 '16 at 10:50
add a comment |
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
4
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
add a comment |
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
4
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
add a comment |
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
It really helps to understand the LINQ query syntax and how it is translated to LINQ method calls.
It turns out that
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending
orderby p.LowestPrice descending
select p;
will be translated by the compiler to
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.OrderByDescending(p => p.LowestPrice)
.Select(p => p);
This is emphatically not what you want. This sorts by Product.LowestPrice.HasValue
in descending
order and then re-sorts the entire collection by Product.LowestPrice
in descending
order.
What you want is
var products = _context.Products
.Where(p => p.ProductTypeId == 1)
.OrderByDescending(p => p.LowestPrice.HasValue)
.ThenBy(p => p.LowestPrice)
.Select(p => p);
which you can obtain using the query syntax by
var products = from p in _context.Products
where p.ProductTypeId == 1
orderby p.LowestPrice.HasValue descending,
p.LowestPrice
select p;
For details of the translations from query syntax to method calls, see the language specification. Seriously. Read it.
edited Aug 21 '13 at 18:35
abc123
13.4k43969
13.4k43969
answered Jun 23 '11 at 22:52
jasonjason
195k28362486
195k28362486
4
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
add a comment |
4
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
4
4
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
+1 or just ... don't write the LINQ query syntax :) Good explanation nonetheless
– sehe
Jun 23 '11 at 23:12
add a comment |
I have another option in this situation.
My list is objList, and I have to order but nulls must be in the end.
my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
add a comment |
I have another option in this situation.
My list is objList, and I have to order but nulls must be in the end.
my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
add a comment |
I have another option in this situation.
My list is objList, and I have to order but nulls must be in the end.
my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
I have another option in this situation.
My list is objList, and I have to order but nulls must be in the end.
my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
answered Mar 21 '12 at 6:32
Gurgen HovsepyanGurgen Hovsepyan
191316
191316
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
add a comment |
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
This can work in scenarios where one wants result with other values like 0 in place of null.
– Naresh Ravlani
Sep 1 '16 at 9:24
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
Yes. Just replace null to 0.
– Gurgen Hovsepyan
Sep 1 '16 at 13:04
add a comment |
The solution for string values is really weird:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
The only reason that works is because the first expression, OrderBy()
, sort bool
values: true
/false
. false
result go first follow by the true
result (nullables) and ThenBy()
sort the non-null values alphabetically.
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);
1
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
add a comment |
The solution for string values is really weird:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
The only reason that works is because the first expression, OrderBy()
, sort bool
values: true
/false
. false
result go first follow by the true
result (nullables) and ThenBy()
sort the non-null values alphabetically.
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);
1
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
add a comment |
The solution for string values is really weird:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
The only reason that works is because the first expression, OrderBy()
, sort bool
values: true
/false
. false
result go first follow by the true
result (nullables) and ThenBy()
sort the non-null values alphabetically.
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);
The solution for string values is really weird:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
The only reason that works is because the first expression, OrderBy()
, sort bool
values: true
/false
. false
result go first follow by the true
result (nullables) and ThenBy()
sort the non-null values alphabetically.
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")
If SomeString
is null, it will be replaced by "z"
and then sort everything alphabetically.
NOTE: This is not an ultimate solution since "z"
goes first than z-values like zebra
.
UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:
public static class MyExtensions
{
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
{
return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
}
}
And simple use it like:
var sortedList = list.NullableOrderBy(f => f.SomeString);
edited Sep 6 '16 at 20:42
answered Apr 8 '16 at 18:44
JaiderJaider
9,08044667
9,08044667
1
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
add a comment |
1
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
1
1
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
I think this is more readable, without the nasty constant: .OrderBy(f => f.SomeString != null ? 0 : 1).ThenBy(f => f.SomeString)
– jornhd
May 4 '16 at 11:44
add a comment |
my decision:
Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)
add a comment |
my decision:
Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)
add a comment |
my decision:
Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)
my decision:
Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)
answered Oct 25 '13 at 8:03
RTKVRTKV
14413
14413
add a comment |
add a comment |
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
add a comment |
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
add a comment |
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
This is what I came up with because I am using extension methods and also my item is a string, thus no .HasValue
:
.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString)
This works with LINQ 2 objects in memory. I did not test it with EF or any DB ORM.
answered Mar 12 '14 at 22:43
AaronLSAaronLS
27.2k15117172
27.2k15117172
add a comment |
add a comment |
I was trying to find a LINQ solution to this but couldn't work it out from the answers here.
My final answer was:
.OrderByDescending(p => p.LowestPrice.HasValue).ThenBy(p => p.LowestPrice)
add a comment |
I was trying to find a LINQ solution to this but couldn't work it out from the answers here.
My final answer was:
.OrderByDescending(p => p.LowestPrice.HasValue).ThenBy(p => p.LowestPrice)
add a comment |
I was trying to find a LINQ solution to this but couldn't work it out from the answers here.
My final answer was:
.OrderByDescending(p => p.LowestPrice.HasValue).ThenBy(p => p.LowestPrice)
I was trying to find a LINQ solution to this but couldn't work it out from the answers here.
My final answer was:
.OrderByDescending(p => p.LowestPrice.HasValue).ThenBy(p => p.LowestPrice)
edited Jan 1 at 8:20
Yodacheese
2,49212032
2,49212032
answered Dec 14 '15 at 11:38
user1user1
8,613561123
8,613561123
add a comment |
add a comment |
Below is extension method to check for null if you want to sort on child property of a keySelector.
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}
And simple use it like:
var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);
add a comment |
Below is extension method to check for null if you want to sort on child property of a keySelector.
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}
And simple use it like:
var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);
add a comment |
Below is extension method to check for null if you want to sort on child property of a keySelector.
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}
And simple use it like:
var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);
Below is extension method to check for null if you want to sort on child property of a keySelector.
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}
And simple use it like:
var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);
edited Jul 9 '18 at 15:43
Noel Widmer
2,42343246
2,42343246
answered Jul 9 '18 at 15:24
Manish PatelManish Patel
83
83
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6461479%2flinq-order-by-null-column-where-order-is-ascending-and-nulls-should-be-last%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
6
orderby p.LowestPrice ?? Int.MaxValue;
is a simple way.– PostMan
Jun 23 '11 at 22:44
2
@PostMan: Yes, it's simple, it achieves the right result, but
OrderByDescending, ThenBy
is clearer.– jason
Jun 23 '11 at 23:30
@Jason, yeah I didn't know the syntax for the
orderby
, and got side tracked looking for it :)– PostMan
Jun 24 '11 at 1:37