简体   繁体   English

按字符串C#的第n个字符对列表进行排序

[英]Sorting a list by the nth character of a string c#

Is there a simple way to sort a list based on the 4th character of a string? 有没有一种简单的方法可以根据字符串的第4个字符对列表进行排序? I have a list of countries with codes in front of them; 我列出了前面有代码的国家/地区; "us united states" is one string in my list and I want to ignore the codes ("us ") before the full country name. “美国”是我列表中的一个字符串,我想忽略全名前的代码(“美国”)。

list.Sort((x, y) => x.Substring(3).CompareTo(y.Substring(3)));

Unlike the other answers, this way of performing the sort will not create unnecessary substrings. 与其他答案不同,这种执行排序的方式不会创建不必要的子字符串。 Instead, it takes advantage of the existing string.Compare(strA, indexA, strB, indexB, length) overload that accepts string offsets for comparison. 而是利用现有的string.Compare(strA,indexA,strB,indexB,length)重载,它接受字符串偏移量进行比较。

list.Sort((s1, s2) => string.Compare(s1, 3, s2, 3, int.MaxValue));

There are other useful string.Compare overloads, that also accept offset values, that you can use to tweak the comparison behavior. 还有其他有用的string.Compare重载也可以接受偏移值,您可以使用它们来调整比较行为。 (eg: ignoring case, etc.) (例如:忽略大小写等)

This should do it - List<string> is your original list variable 应该这样做List<string>是您的原始列表变量

[List<string>].OrderBy(s => s.Substring(3)).ToList();

This works 这有效

var l = new List<string>(){"us unites states","uk united kingdom","ca canada"};
foreach (var s in l.OrderBy(s => s.ToLower().Substring(3)).ToList())
    Console.WriteLine(s);

Note ToLower , so you don't compare upper case to lower case letters (if you have both) 注意ToLower ,因此不要将大写字母与小写字母进行比较(如果同时具有)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM