如何使用 LINQ 对后跟数字的文本字符串进行排序 [英] How can I sort a string of text followed by a number using LINQ

查看:28
本文介绍了如何使用 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 解析为最后给你(我假设)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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆