MetaGuru
MetaGuru

Reputation: 43813

What do I pass into List<Object>.Sort() to sort the items least to greatest by Object.SomeInteger?

List<MyObject> myList = new List<MyObject>();

foreach(SomeObject obj in someObjects)
{
     MyObject mo = new MyObject();

     mo.SomeInteger = obj.OriginalInteger;
     mo.OtherRandomData = obj.OtherRandomData;

     myList.Add(obj);
}

myList.Sort(/* NOT SURE WHAT TO WRITE HERE */);

So that in the end MyObjects in myList are ordered least to greatest by SomeInteger.

Upvotes: 2

Views: 934

Answers (5)

lost_in_the_source
lost_in_the_source

Reputation: 11237

myList.Sort();
myList.Reverse();

This simple code should order it from least to greatest. But since greatest to least is just the reverse of least to greatest, I used the Reverse function.

Upvotes: 0

Steven
Steven

Reputation: 172646

You can take the Sort overload that takes a Comparison<T> delegate:

myList.Sort((x, y) => x.SomeInteger.CompareTo(y.SomeInteger));

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500385

Steven's answer is fine, but if you're using .NET 3.5 or higher you should also consider using LINQ. Your entire code can be written as:

var myList = (from obj in someObjects
              orderby obj.OriginalInteger
              select new MyObject { SomeInteger = obj.OriginalInteger,
                                   OtherRandomData = obj.OtherRandom Data })
             .ToList();

Note that this is ordering by the original data, rather than building the MyObject values first and then sorting. You can also write this as:

var myList = someObjects.OrderBy(obj => obj.OriginalInteger)
                        .Select(obj => new MyObject { 
                                   SomeInteger = obj.OriginalInteger,
                                   OtherRandomData = obj.OtherRandom Data })
                        .ToList();

Note that if you ever want to sort by more than one property, this is really easy with LINQ but can be a bit cumbersome with List<T>.Sort.

Upvotes: 3

John Fisher
John Fisher

Reputation: 22719

You can look at this sample: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

Or, you can do things the Linq way:

myList = myList.OrderBy(x => x.SomeInteger).ToList();

Upvotes: 0

KeithS
KeithS

Reputation: 71563

You can also use OrderBy(), which avoids having to specify the full Comparison logic:

myList = myList.OrderBy(x=>x.SomeInteger).ToList();

This will be slower than List.Sort(), and SomeInteger must be IComparable (all ValueTypes are), but the sort will be stable (in the case of "ties", items preserve their relative order from the unsorted list).

Upvotes: 0

Related Questions