通过使用 C# 的最后 3 个字符按字母顺序排列列表?
Alphabetize list by using last 3 characters with C#?
我有一个这样的字符串列表:
- 123.45 ABC
- 678.90 防御力
- 543.21 美联储
我想使用每个列表元素的最后 3 个字符按字母顺序对列表进行排序。
编辑:使用 C#,如何使用每个元素的最后 3 个字符按字母顺序排列此列表?
要按最后三个字符排序,您可以只使用从 Length - 3
开始的 Substring
并在 OrderBy
方法中使用它(注意我们应该首先检查 item.Length > 2
这样 Substring
就不会抛出异常):
var items = new List<string> {"543.21 FED", "123.45 ABC", "678.90 DEF"};
items = items
.OrderBy(item => item?.Length > 3 ? item.Substring(item.Length - 3) : item)
.ToList();
// result: {"123.45 ABC", "678.90 DEF", "543.21 FED"}
或者,您可以为字符串编写自定义比较器,然后将其传递给 Sort
方法。我们可以为我们的比较器包含一个构造函数,它接受一个 int
指定我们想要从字符串末尾计算多少个字符以使其更灵活(比如如果你想使用最后一个 5
个字符,或最后一个 2
,等等)。
public class OrderByLastNChars : Comparer<string>
{
public int N { get; set; }
public OrderByLastNChars(int n)
{
N = n;
}
public override int Compare(string x, string y)
{
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
var first = x.Length > N ? x.Substring(x.Length - N) : x;
var second = y.Length > N ? y.Substring(x.Length - N) : y;
return first.CompareTo(second);
}
}
然后可以这样使用:
items.Sort(new OrderByLastNChars(3));
我首先要做的是确保过滤掉所有少于 3 个字符的字符串。然后我将它们订购为:
var items = new List<string> { "13 zzz", "12 yyy", "11 zzz" };
items = items.Where(i => i.Length > 2)
.OrderBy(i => i.Substring(i.Length - 3))
.ToList();
我有一个这样的字符串列表:
- 123.45 ABC
- 678.90 防御力
- 543.21 美联储
我想使用每个列表元素的最后 3 个字符按字母顺序对列表进行排序。
编辑:使用 C#,如何使用每个元素的最后 3 个字符按字母顺序排列此列表?
要按最后三个字符排序,您可以只使用从 Length - 3
开始的 Substring
并在 OrderBy
方法中使用它(注意我们应该首先检查 item.Length > 2
这样 Substring
就不会抛出异常):
var items = new List<string> {"543.21 FED", "123.45 ABC", "678.90 DEF"};
items = items
.OrderBy(item => item?.Length > 3 ? item.Substring(item.Length - 3) : item)
.ToList();
// result: {"123.45 ABC", "678.90 DEF", "543.21 FED"}
或者,您可以为字符串编写自定义比较器,然后将其传递给 Sort
方法。我们可以为我们的比较器包含一个构造函数,它接受一个 int
指定我们想要从字符串末尾计算多少个字符以使其更灵活(比如如果你想使用最后一个 5
个字符,或最后一个 2
,等等)。
public class OrderByLastNChars : Comparer<string>
{
public int N { get; set; }
public OrderByLastNChars(int n)
{
N = n;
}
public override int Compare(string x, string y)
{
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
var first = x.Length > N ? x.Substring(x.Length - N) : x;
var second = y.Length > N ? y.Substring(x.Length - N) : y;
return first.CompareTo(second);
}
}
然后可以这样使用:
items.Sort(new OrderByLastNChars(3));
我首先要做的是确保过滤掉所有少于 3 个字符的字符串。然后我将它们订购为:
var items = new List<string> { "13 zzz", "12 yyy", "11 zzz" };
items = items.Where(i => i.Length > 2)
.OrderBy(i => i.Substring(i.Length - 3))
.ToList();