What is the best way to sort a List of objects with a start value?
c#, linq, sorting
Solution
Use `OrderBy` and `ThenBy` combination. It will work with `using System.Linq` at top of your file.
var source = new List<Item>() {
new Item { index = 1, value = 'a' },
new Item { index = 3, value = 'b' },
new Item { index = 2, value = 'c' },
new Item { index = 4, value = 'd' },
};
int startValue = 3;
var sortedList = source.OrderBy(i => i.index < startValue)
.ThenBy(i => i.index)
.ToList();
foreach (var item in sortedList)
Console.WriteLine(string.Format("{0} - {1}", item.value, item.index));
`Item` class definition:
class Item
{
public char value { get; set; }
public int index { get; set; }
}
Returns desired output:
b - 3
d - 4
a - 1
c - 2
Problem
What is the best way to sort a List of object with a start value? My list has the items: ``` obj a obj b obj c obj d a.index = 1 b.index = 3 c.index = 2 d.index = 4 start value = 3; ``` sorted list must be `{b,d,a,c}` Thanks for help.