根据对象的属性对强类型对象的数组进行排序

时间:2009-07-31 09:42:24

标签: c# arrays

我有array[]个对象,由于某些原因我无法将其更改为List<>,是否可以根据1中的值对array[]个对象进行排序对象的领域?

例如

arrayOfFruit[] fruit; 

fruit.sort(name);

4 个答案:

答案 0 :(得分:2)

使用Array .. ::。Sort Method(Array,IComparer)

http://msdn.microsoft.com/en-us/library/aw9s5t8f.aspx

答案 1 :(得分:1)

如果要清楚区分选择器 comparer ,可以使用此助手类。太糟糕了,你不能使用“类扩展方法”来为Array.Sort提供一组带选择器的重载。

public static class SelectingComparer<T>
{
    public static IComparer<T> Create<U>(Func<T, U> selector)
    {
        return new SelectingComparerImpl<U>(selector, null);
    }

    public static IComparer<T> Create<U>(Func<T, U> selector, IComparer<U> comparer)
    {
        return new SelectingComparerImpl<U>(selector, comparer.Compare);
    }

    public static IComparer<T> Create<U>(Func<T, U> selector, Comparison<U> comparison)
    {
        return new SelectingComparerImpl<U>(selector, comparison);
    }

    private class SelectingComparerImpl<U>
        : IComparer<T>
    {
        private Func<T, U> selector;
        private Comparison<U> comparer;

        public SelectingComparerImpl(Func<T, U> selector, Comparison<U> comparer)
        {
            if (selector == null)
                throw new ArgumentNullException();

            this.selector = selector;
            this.comparer = comparer ?? Comparer<U>.Default.Compare;
        }

        public int Compare(T x, T y)
        {
            return this.comparer(this.selector(x), this.selector(y));
        }
    }
}

使用中:

public class Testing
{
    public void Foo()
    {
        FileInfo[] files = new FileInfo[30];
        // FILL THE FILE ARRAY
        Array.Sort(files, SelectingComparer<FileInfo>.Create(file => file.Name));
        Array.Sort(files, SelectingComparer<FileInfo>.Create(file => file.Name, StringComparer.OrdinalIgnoreCase));
    }
}

答案 2 :(得分:0)

您可以使用IComparer作为排序参数

答案 3 :(得分:0)

void SomeMethod()
{
    Fruit fruits[] = GetArrayOfFruit();
    Array.Sort(fruits, FruitNameComparer);
}

int FruitNameComparer(Fruit lhsOfQEquals, Fruit rhsOfEquals)
{
    return String.Compare(lhsOfQEquals.Name, rhsOfEquals.Name);
}