tags:

views:

197

answers:

3

so i have my class, here:

MyClass
{
  public MyClass(Sort sort, string name){ this.srt = sort; this.Name = name; }
  public enum Sort { First, Second, Third, Fourth }
  public Sort srt { get; set; }
  public string Name { get; set; }
}

I have a list full of entries of MyClass, and I'm looking to sort them into groups by their srt property, and then alphabetize those groups. for instance

List<MyClass> list = new List<MyClass>() { 
  new MyClass(MyClass.Sort.Third, "B"), 
  new MyClass(MyClass.Sort.First, "D"),
  new MyClass(MyClass.Sort.First, "A"),
  new MyClass(MyClass.Sort.Fourth, "C"),
  new MyClass(MyClass.Sort.First, "AB"),
  new MyClass(MyClass.Sort.Second, "Z")
};

then id like the output to be: (showing Name)

A
AB
D
Z
B
C

So to sum it up once again, i need to sort the list into sections by the enum, and then sort the sections by name. (NOTE: i just used this class as an example therefore, the enum isnt just going to be first, second etc, all the text values are names of things... but i do want to be able to choose the order of the sections.)

Ive played with using some foreach(var in list) to separate them into their sections, but this just seems slow and ineffective, as ill be doing this LOTS of times, with large lists.

Then i thought, maybe LINQ, or some compare method, but I'm not sure how that would be done!

Thanks for any responces!

+6  A: 

Using extension methods, first OrderBy the enum, ThenBy name.

var sorted = list.OrderBy( m => m.Sort ).ThenBy( m => m.Name );
tvanfosson
+1 beat me by 4 secs :)
Ahmad Mageed
+3  A: 

This should do it, I think

var result = from m in list
             orderby m.Sort, m.Name
             select m;
pdr
This syntax is not valid. The `select m` needs to be placed at the end, then it'll be correct.
Ahmad Mageed
Thanks Ahmed, corrected. 3am fail
pdr
+3  A: 

Aside from the nice LINQ solutions, you can also do this with a compare method like you mentioned. Make MyClass implement the IComparable interface, with a CompareTo method like:

  public int CompareTo(object obj)
  {
      MyClass other = (MyClass)obj;
      int sort = this.srt.CompareTo(other.srt);
      return (sort == 0) ? this.Name.CompareTo(other.Name) : sort;
  }

The above method will order your objects first by the enum, and if the enum values are equal, it compares the name. Then, just call list.Sort() and it will output the correct order.

wsanville