How to sort part of items in generic list
I have a List object that contains items in following type
public class Item{
public int Type; //this can be only 0 or 1
public string Text;
}
I would like to sor开发者_StackOverflow中文版t the entire list by the Type first and then do another sort by Text for only items that have type is 1?
How to achieve this?
Many thanks
Ming
Here's how I'd do it.
var ordered = list.OrderBy(i => i.Type == 0 ? "" : i.Text);
This is assuming there are no empty Text strings where i == 0. If you can't make that assumption, the following would work:
var ordered = list.OrderBy(i => i.Type).ThenBy(i => i.Type == 0 ? "" : i.Text);
By giving all items with a 0 Type the same value, you'll leave them all in their initial order, while sorting other items by their Text value.
On a side note, this is a code smell:
public int Type; //this can be only 0 or 1
At a glance, that sounds like it ought to be a boolean or a custom enum
type. After taking a deeper look at what you're trying to do, it sounds like maybe you're not expecting Text
to even be a legitimate value if Type is 0. If that's the case, you should consider using class inheritance to actually differentiate one item type from another.
Your question isn't perfectly clear. It sounds like you want TWO different sorts, not a sort on one field, and then a stable re-sort when the Type
equals 1
?
Assuming the former:
var sortByType = items.OrderBy(x => x.Type)
.ToList();
var sortTheOnesByText = items.Where(x => x.Type == 1)
.OrderBy(x => x.Text)
.ToList();
List<Item> items;
items = items.OrderBy(i => i.Type).ThenBy(i => i.Type == 1 ? i.Text : null);
Implement IComparable<Item>
See details with example msdn
And than just use List<T>.Sort()
method
I think you mean you want to put all the type=0 at the front and all the type=1 at the back, and also sort by text where type=1.
items.OrderBy(item => item.Type).ThenBy (item => type == 0 ? "" : item.Text)
If you don't mind ordering Type 0 items as well then you can do
var sortedItems = items.OrderBy(i => i.Type).ThenBy(i => i.Text);
Otherwise, if you need to preserve the original order for Type 0 items, then you can do
var sortedItems = items.OrderBy(i => i.Type).ThenBy(i => i.Type == 0 ? "A" : i.Text);
精彩评论