gpt4 book ai didi

c# - 实现自定义 IComparer<>(附示例)

转载 作者:太空狗 更新时间:2023-10-30 01:22:01 31 4
gpt4 key购买 nike

我刚刚编写了以下代码,它将按其 native string.Compare() 对字符串进行排序,但允许异常集合(在本例中为 customPriority)优先于默认的 string.Compare() 函数。

这一切似乎有点啰嗦,我想知道 .NET 中是否内置了一些东西来允许这样做?

    var unorderered = new[] { "a", "b", "c", "x", "y", "z" };
var ordered = unorderered.OrderBy(a => a, new CustomStringComparer());
//expected order y,x,a,b,c,z

class CustomStringComparer : IComparer<string>
{
int IComparer<string>.Compare(string x, string y)
{
if (x == y)
return 0;
else
{
//----------------------------
//beginning of custom ordering
var customPriority = new[] { "y", "x" };
if (customPriority.Any(a => a == x) && customPriority.Any(a => a == y)) //both in custom ordered array
{
if (Array.IndexOf(customPriority, x) < Array.IndexOf(customPriority, y))
return -1;
return 1;
}
else if (customPriority.Any(a => a == x)) //only one item in custom ordered array (and its x)
return -1;
else if (customPriority.Any(a => a == y)) //only one item in custom ordered array (and its y)
return 1;
//---------------------------
//degrade to default ordering
else
return string.Compare(x, y);

}
}
}

最佳答案

首先,我认为重述问题很有用:您想按以下方式排序:

  1. 给定数组中的索引;如果该项目不在数组中,则索引为无穷大
  2. 字符串本身

这意味着您可以通过对第一个条件使用 OrderBy() 然后对第二个条件使用 ThenBy() 来实现您的排序顺序:

private static uint NegativeToMaxValue(int i)
{
if (i < 0)
return uint.MaxValue;
return (uint)i;
}



var ordered = unorderered
.OrderBy(a => NegativeToMaxValue(Array.IndexOf(new[] { "y", "x" }, a)))
.ThenBy(a => a);

NegativeToMaxValue() 是必要的,因为不在数组中的项目应该是最后的,但它们通常是第一个,因为索引是 -1。 (一种骇人听闻且不可读的方法是直接将 IndexOf() 的结果转换为 uint。)

如果您想通过创建一个 IComparer 来重用这种排序,我相信 .Net 中没有任何东西可以帮助您实现这一点。但是你可以使用 ComparerExtensions相反:

IComparer<string> comparer = KeyComparer<string>
.OrderBy(a => NegativeToMaxValue(Array.IndexOf(new[] { "y", "x" }, a)))
.ThenBy(a => a);

关于c# - 实现自定义 IComparer<>(附示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14707650/

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