0

I have an array[] of objects, for certain reasons I cannot change it to a List<>, is it possible to sort on the array[] of objects, based on a value in 1 field of the object?

For example

arrayOfFruit[] fruit; 

fruit.sort(name);
2
  • Duplicate from a few days ago... searching... Commented Jul 31, 2009 at 9:43
  • Related: How to sort an array of FileInfo[] Commented Jul 9, 2018 at 14:21

4 Answers 4

2

Use Array..::.Sort Method (Array, IComparer)

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

Sign up to request clarification or add additional context in comments.

Comments

1

If you want a clean distinction of the selector and comparer, you can use this helper class. It's too bad you can't have a "class extension method" to give Array.Sort a set of overloads that take a selector.

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

In use:

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

Comments

0

You can use a IComparer as a parameter of sort

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.