如何使用LINQ对文本字符串和数字进行排序 [英] How can I sort a string of text followed by a number using LINQ
问题描述
我一直在使用以下排序:
I have been using the following sort:
var query = _cityRepository.GetAll(
.OrderBy(item => item.RowKey.Substring(0, 4))
.ThenBy(item => item.ShortTitle)
但是我遇到了问题,因为我的ShortTitle看起来像这样:
However I am having a problem because my ShortTitle looks like this:
Liverpool - 1
Liverpool - 2
...
Liverpool - 9
Liverpool - 10
Liverpool - 11
West Kirby - 1
West Kirby - 8
West Kirby - 12
当我使用LINQ对它进行排序时,它的顺序是
When I sort this using LINQ it comes in the order
Liverpool - 1
Liverpool - 11
Liverpool - 12
Liverpool - 2
West Kirby - 1
West Kirby - 12
West Kirby - 8
ShortTitle始终是一串单词,后跟一个连字符和一个数字.
The ShortTitle is always a string of words followed by a single hyphen and then a number.
有没有办法让我对它进行正确排序?
Is there a way I can get this to sort correctly?
推荐答案
这是因为您正在将它们排序为字符串,并且对于字符串11在2之前.您需要解析ShortTitle
来给您( 'm假设)最后加上int
值,然后按该值排序.
It's because you are sorting them as strings, and for strings 11 comes before 2. You'll need to parse the ShortTitle
to give you the (I'm assuming) int
value at the end, and sort by that.
您的LINQ查询可以更改为此,以使其正常工作:
Your LINQ query can be changed to this for it to work:
var query = _cityRepository.GetAll(
.OrderBy(item => item.RowKey.Substring(0, 4))
.ThenBy(item => item.ShortTitle.Split('-').First())
.ThenBy(item => Convert.ToInt16(item.ShortTitle.Split().Last()));
这篇关于如何使用LINQ对文本字符串和数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!