[英]Can I use Linq to create a comparer for a C# sorted dictionary
有没有办法使用Linq创建SortedDictionary? 这将避免创建比较器类的不便(和代码膨胀)。
例如,创建一个按字符串键反向排序的字典:
//NOT VALID SYNTAX
SortedDictionary<string, int> sortDict = new SortedDictionary(kvp => new String(kvp.Key.Reverse().ToArray());
//VALID SYNTAX
SortedDictionary<string, int> sortDict = new SortedDictionary<string, int>(new ReverseStringComparer);
private class ReverseStringComparer: IComparer<String>
{
public int Compare(string x, string y)
{
string s1 = new string(x.Reverse().ToArray());
string s2 = new string(y.Reverse().ToArray());
return s1.CompareTo(s2);
}
}
您可以定义一个通用比较器类,它将提取功能应用于您要比较的项目:
public class KeyComparer<TItem, TKey> : Comparer<TItem>
{
private readonly Func<TItem, TKey> extract;
private readonly IComparer<TKey> comparer;
public KeyComparer(Func<TItem, TKey> extract)
: this(extract, Comparer<TKey>.Default)
{ }
public KeyComparer(Func<TItem, TKey> extract, IComparer<TKey> comparer)
{
this.extract = extract;
this.comparer = comparer;
}
public override int Compare(TItem x, TItem y)
{
// need to handle nulls
TKey xKey = extract(x);
TKey yKey = extract(y);
return comparer.Compare(xKey, yKey);
}
}
我通常使用这个类来提取属性; 但是,您可以定义任何函数,例如字符串反转:
SortedDictionary<string, int> sortDict = new SortedDictionary<string, int>(
new KeyComparer<string, string>(s => new string(s.Reverse().ToArray())));
更新 :我在博文中更详细地介绍了这个比较器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.