C#List< string>按拆分排序 [英] C# List<string> OrderBy Split
问题描述
我试图按拆分后的值对列表进行排序.
I'm trying to just Order a list by the value after a split.
例如,我的数据如下所示.
For example my data looks like this.
Z|2
A|1
我希望我的列表按拆分后的值排序
I want my list to be order by the value after the split
所以我会得到
A|1
Z|2
这是我正在使用的,但出现错误:
This is what i'm using but I get the error:
{输入字符串的格式不正确."}
All = All.OrderBy(s => int.Parse(s.Split('|')[1])).ToList();
任何帮助都会很棒!谢谢!
Any help would be awesome! Thanks!
推荐答案
这将起作用:
All = All.OrderBy(s => int.Parse(s.Split('|').Last())).ToList();
更好的方法是拥有结构化类型的列表,而不是哑字符串的列表.例如,您可能具有Tuple<string, int>
的列表,并仅按第二个成员对其进行排序.您还可以将元组放入有序容器中,并自动完成排序.
What would work even better though would be to have a list of a structured type instead of a list of dumb strings. For example, you could have a list of Tuple<string, int>
and simply sort it by the second member. You could also put the tuple into an ordered container and have sorting done automatically.
这篇关于C#List< string>按拆分排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!