views:

1271

answers:

2

Greetings! I want to use LINQ to query a list of objects and sort them by an enumeration value, string value then union the rest of the list sorted in a similar fashion LINQ newbie here, so be gentle.

//CTOR for my class
MyClass(id, "Name Value Here", Enum.EnumValueHere);

I create a list of these objects and want to variably sort them such that all items with Enum.EnumValue[X] are shown first in the list, sorted by Name, followed by all other items sorted in a similar fashion (almnost like a Union of result sets in SQL)

//What I have so far (only sorts the list)
List<MyClass> = (from s in MyClass orderby s.EnumValue, s.NameValue  select s).ToList();

Any Guru's out there have some LINQ Magic to share?

Thanks!

A: 

You could take the first list and do a list.AddRange() which takes an ienumerable.

yieldvs
+2  A: 

Not sure exactly what you mean, but could you use something like this?

// Using Color as enum just to make things clearer
class ClassyClass
{
    public string Name {get; private set;}
    public Color Color {get; private set;}
    public ClassyClass(id, string name, Color color) { ... }
}


var orderedList = collectionOfClassyClasses
            .OrderBy(x => x.Color != Color.Red) // False comes before true
            .ThenBy(x => x.Color)
            .ThenBy(x => x.Name)
            .ToList();

If collectionOfClassyClasses was some sort of collection of ClassyClass objects, then orderedList would be ordered so that all those with Color set to Red would come first, ordered by name, and then all the others ordered by color and then name. At least I think it would... haven't tested it :p Let me know if it doesn't, hehe.

Svish
Thank's for your response. Your edit proved to be correct, in that false is evaluated b4 true...your solution works great, thanks a ton!
Great to hear it worked out :) I'll remove the edit and fix the code so that it is correct instead =)
Svish