0

I have an object that has two members that are both integer values. I made an array of these objects. Each objects values are filled with random integers.

I want to sort the array of objects according to the first member value. How would I do this?

3 Answers 3

7

Are you using .NET 3.5? If so, it's as easy as:

array = array.OrderBy(x => x.MemberName).ToArray();

That will create a new array though - if any other code has a reference to the old array, it will still see the unsorted data.

Alternatively, you can use the Array.Sort method which will sort the array in-place, in one of three ways:

  • Make your type implement IComparable<T> allowing an object to compare itself with another
  • Create an instance of IComparer<T> which can compare any two objects of that type
  • Create a delegate of type Comparison<T> which can compare any two objects of that type

The last is probably the easiest solution if you're using C# 3:

Array.Sort(array, (x1, x2) => x1.MemberName.CompareTo(x2.MemberName));
Sign up to request clarification or add additional context in comments.

Comments

1

You have to implement IComparable in the class first. These should help:
Sort ArrayList Of Objects
How to use the IComparable and IComparer interfaces in Visual C#

Comments

0
class Program
{
    class Foo
    {
        public int FirstMemberValue { get; set; }
    }

    static void Main(string[] args)
    {
        var foos = new[] 
        { 
            new Foo { FirstMemberValue = 1 }, 
            new Foo { FirstMemberValue = 3 }, 
            new Foo { FirstMemberValue = 2 } 
        };
        Array.Sort(foos, (f1, f2) => f1.FirstMemberValue.CompareTo(f2.FirstMemberValue));
        foreach (var item in foos)
        {
            Console.WriteLine(item.FirstMemberValue);
        }
    }
}

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.