Linq - 按数字然后字母排序
我有一个字符串列表,这些字符串包含数字和单词。
我想做的是按数字(数字顺序)后跟单词(字母顺序)对其进行排序
我的列表不包含两者的混合...这是一个示例
1、5、500、LT、RT、400→ LINQ-> 1、 5、400、500、LT、RT
这是我的一个例子,它有效,但我想知道是否有更好的写法?
int results = 0;
// Grabs all voltages
var voltage = ActiveRecordLinq.AsQueryable<Equipment>()
.OrderBy(x => x.Voltage)
.Select(x => x.Voltage)
.Distinct()
.ToList();
// Order by numeric
var numberVoltage = voltage
.Where( x => int.TryParse(x, out results))
.OrderBy( x => Convert.ToInt32(x));
// Then by alpha
var letterVoltage = voltage
.Where(x=> !String.IsNullOrEmpty(x))
.Where(x => !int.TryParse(x, out results))
.OrderBy(x => x);
return numberVoltage.Union(letterVoltage)
感谢您的帮助!
I have a list of strings, and these strings contain numbers and words.
What I wanted to do is order it by the numbers (numeric order) followed by the words (alphabetical order)
My list does not contain a mix of the two... here is an example
1, 5, 500 , LT, RT, 400 -> LINQ -> 1,
5, 400, 500, LT, RT
Here is a example of what I have, it works but I was wondering if there is a better way of writing it?
int results = 0;
// Grabs all voltages
var voltage = ActiveRecordLinq.AsQueryable<Equipment>()
.OrderBy(x => x.Voltage)
.Select(x => x.Voltage)
.Distinct()
.ToList();
// Order by numeric
var numberVoltage = voltage
.Where( x => int.TryParse(x, out results))
.OrderBy( x => Convert.ToInt32(x));
// Then by alpha
var letterVoltage = voltage
.Where(x=> !String.IsNullOrEmpty(x))
.Where(x => !int.TryParse(x, out results))
.OrderBy(x => x);
return numberVoltage.Union(letterVoltage)
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
鉴于您正在进程中完成所有操作(因为您有一个 ToList 调用),我想我只需使用自定义比较器:
其中
AlphaNumericComparer
实现IComparer< /code>,类似这样:
您可以为后一部分使用一个巨大的条件:
...但在这种情况下,我认为我不会:)
Given that you're doing it all in-process (as you've got a ToList call) I think I'd just use a custom comparer:
Where
AlphaNumericComparer
implementsIComparer<string>
, something like this:You could use a giant conditional for the latter part:
... but in this case I don't think I would :)
此解决方案尝试对每个值解析一次。
This solution attempts parsing once for each value.