gpt4 book ai didi

c# - 使用 LINQ 和函数自定义排序

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:26 24 4
gpt4 key购买 nike

我有一个字符串列表,每个字符串的长度正好是 2 个字符。我想整理一下。我首先使用

按每个字符串的第一个字符对列表进行排序
.OrderBy(e => e[0])

但我的问题是在对第二个字符进行排序时,类似于:

.ThenBy(string1 => string1, string2 => string2 Compare(string1,string2)

我想选择两个字符串并将它们传递给我创建的名为 compare 的函数。

有人可以告诉我该怎么做吗,或者是否有更好的方法来做我想做的事情?请分享。

public string sortT(string h)
{
var sortedList = l
.OrderBy(e => e[0])
.ThenBy()
.ToList<string>();
return sb.ToString();
}
private int Compare(string a, string b)
{
List<char> value = new List<char>() {
'2', '3', '4', '5', '6', '7', '8', '9','J','Q', 'K', 'A' };
if (value.IndexOf(a[1]) > value.IndexOf(b[1]))
return 1;
return -1;
}

最佳答案

您可以使用您的列表作为基础:

List<char> value = new List<char>() { '2', '3', '4', '5', '6', '7', '8', '9','J','Q', 'K', 'A' };

var sortedList = l.OrderBy(str => str[0])
.ThenBy(str => value.IndexOf(str[1]))
.ToList<string>();

您还可以实现自定义 IComparer<T>像这样:

public class TwoCharComparer : IComparer<string>
{
private static readonly List<char> value = new List<char>() { '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A' };

public int Compare(string x, string y)
{
if (x == null || y == null || x.Length < 2 || y.Length < 2) return 0; // ignore
int comparison = x[0].CompareTo(y[0]);
if (comparison != 0)
return comparison;
int ix1 = value.IndexOf(x[1]);
int ix2 = value.IndexOf(y[1]);
if(ix1 == ix2 && ix1 == -1)
return x[1].CompareTo(y[1]);
else
return ix1.CompareTo(ix2);
}
}

现在您可以将其传递给 List.Sort不需要创建新列表:

var l = new List<string> { "C1", "B2", "A2", "B1", "A1", "C3", "C2" };
l.Sort(new TwoCharComparer()); // A1,A2,B1,B2,C1,C2,C3

关于c# - 使用 LINQ 和函数自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25681083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com