我可以使用Linq为C#排序字典创建比较器

时间:2014-02-04 10:57:54

标签: c# sorting dictionary icomparer

有没有办法使用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);
    }
}

1 个答案:

答案 0 :(得分:3)

您可以定义一个通用比较器类,它将提取功能应用于您要比较的项目:

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())));

更新:我已在blog post更详细地介绍了此比较器。