开发者

Equivalent sorting with LINQ orderby keyword vs. OrderBy extension method

开发者 https://www.devze.com 2023-03-08 03:44 出处:网络
I\'m trying to come up with a set of chained OrderBy/ThenBy extension method calls that is equivalent to a LINQ statement using the orderby keyword.

I'm trying to come up with a set of chained OrderBy/ThenBy extension method calls that is equivalent to a LINQ statement using the orderby keyword.

My LINQ statement using the orderby keyword looks like this:

List<Summary> sortedSummaries = new List<Summary>(
    from summary in unsortedSummaries
    orderby summary.FieldA ascending,
            summary.FieldB ascending,
            summary.FieldC ascending,
            summary.FieldD ascending
    select summary);

Now, I would guess that an equivalent version, using chained OrderBy/ThenBy extension method calls would look like this:

List<Summary> sortedSummaries = new List<Summary>(unsortedSummaries);    
sortedSummaries.OrderBy(x => x.FieldA).ThenBy(x => x.FieldB).ThenBy(x => x.FieldC).ThenBy(x => x.FieldD);

However, this gives me quite different results than using my LINQ statement using the orderby keyword.

What might I be doing wrong here?


The reason I'm trying to convert to using chained OrderBy/ThenBy extension method calls is that I need to use a custom comparer on FieldD, like so:

.ThenBy(x => x.FieldD, new NaturalSortComparer())

I can't figure how to do that using LINQ statements with the orderby keyword, so I thought using extension methods might get me farther, but since I'm not able to get my extension method version to give me the same results as my orderby keyword version, I'm back to the drawing board, for the moment.

开发者_如何学PythonAny ideas?


Your dot notation call isn't assigning the result to anything. It ought to be:

var sortedSummaries = unsortedSummaries.OrderBy(x => x.FieldA)
                                       .ThenBy(x => x.FieldB)
                                       .ThenBy(x => x.FieldC)
                                       .ThenBy(x => x.FieldD);

Don't forget that LINQ operators never change the existing sequence - they return a new sequence with the appropriate differences (in this case, ordering). If you want to sort in-place, use List<T>.Sort.

The query above is exactly what the LINQ part of your original code does. However, if I wanted to construct a list from it, I wouldn't pass it to the List<T> constructor - I'd use the ToList extension method:

var sortedSummaries = unsortedSummaries.OrderBy(x => x.FieldA)
                                       .ThenBy(x => x.FieldB)
                                       .ThenBy(x => x.FieldC)
                                       .ThenBy(x => x.FieldD)
                                       .ToList();

Check that that does what you expect it to (it really should) - and then you can put your custom comparison in.

0

精彩评论

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