views:

133

answers:

3

I have a List sort question. I am using c# 3.0 and a generic List structure like this:

public class myObject
{
    public int ID { get; set; }
    public List<mySetting> setting { get; set; }
}

public class mySetting
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }  // sort on this!
}

with this structure, I am filling a List of myObject with a LINQ query.

List<myObject> lmo = new List<myObject>();
lmo.SomeFillOperation():

What I want to do now is sort the entire List<myObject> on the individual <mySetting>[].Value values. EDIT: ( So this would be sorting on one keyed index of , for example mySetting[3].Value). I realize I could possibly do it in my SomeFillOperation(), but I want to do it after the List is formed.

Is there a recommended or easy way to do this? Is there a good example you have seen? Thanks in advance!

+3  A: 

Well, List<T> already has a Sort method if you want to sort it in place - or you could use LINQ's OrderBy method. OrderBy is slightly easier than Sort:

var sorted = lmo.OrderBy(x => x.Value);

but even Sort isn't too bad:

lmo.Sort((x, y) => x.Value.CompareTo(y.Value));

EDIT: Having read the comment to the question, I no longer understand the question! Leaving this answer here as a potentially useful placeholder while I have dinner...

Jon Skeet
A: 

Since you are using 3.0, use LINQ:

var newList = lmo.OrderBy(i => i.Value);

and

var newList = lmo.OrderByDescending(i => i.Value);
Andrew Robinson
+1  A: 
int MyObjectComparison(MyObject x, MyObject y)
{
     return x.setting[0].Value.CompareTo(y.setting[0].Value);
}

lmo.Sort(MyObjectComparison);

Of course, this assumes that you want to use the Value of the first element in setting (and that setting is guarunteed to have at least one element). Solution with less assumption will be forthcoming when more info is given.

James Curran