To order a list with Linq, we must call OrderBy first en call ThenBy for the result for subordinate orders.
Now I am in a situation where I do not know how to order the upper level before hand. I have a list of orders that should be applied conditionally.
Like this:
var list = new List<Tuple<int, string, DateTime>>(); list.Add(new Tuple<int, string, DateTime>(1, "B", new DateTime(2020, 1, 1))); list.Add(new Tuple<int, string, DateTime>(2, "A", new DateTime(2000, 1, 1))); list.Add(new Tuple<int, string, DateTime>(3, "C", new DateTime(1900, 1, 1))); var orderedList = list; if (sortByString) { orderdedList = orderedList.ThenBy(listItem => listItem.Item2); } if (sortByDateTime) { orderedList = orderedList.ThenBy(listItem => listItem.Item3); } orderList = orderedList.ThenBy(listItem => listItem.Item1);
Thus, the list will always be ordered by Item1 and, conditionally, by Item2 and / or Item3.
How to do it in C #? Solutions without Linq are also welcome.
source share