C #: Sort / OrderBy Enum Value

I have an IEnumerable that I implemented from Linq2Sql. I have already filtered out the records I want, now I want to order them based on the selected enumeration:

public enum Sort { Time, Name, Value } public class LinqClass { public DateTime Time; public string Name; public double Value; } Sort sort = Sort.Time items.OrderBy(sort); 

What is the best way to do this? I could create an overloaded OrderBy (Sort), which is just a big switch statement:

 switch(sort) case Time: return this.OrderBy(x=>x.Time); 

Perhaps I could do something with the dictionary. Any other ideas, or there is a standard template for this.

+4
source share
2 answers

The switch statement is probably the best approach, as it makes it easy to determine when an invalid value was passed.

You can use Dictionary<Sort, Func<IEnumerable<LinqClass>, IEnumerable<LinqClass>>> , but I don't think it's worth it.

+3
source

If you understand the data as a List , you can use the Sort method, which accepts the Comparison delegate and selects a comparison with the dictionary:

 var comparisons = new Dictionary<Sort, Func<LinqClass, LinqClass, int>(); sorting.Add(Sort.Time, (x, y) => x.Time.CompareTo(y.Time)); sorting.Add(Sort.Name, (x, y) => x.Name.ComapreTo(y.Name)); sorting.Add(Sort.Value, (x, y) => x.Value.CompareTo(y.Value)); items.Sort(comparisons[sort]); 
+1
source

Source: https://habr.com/ru/post/1389937/


All Articles