Linq OrderBy against specific values

后端 未结 8 1740
悲&欢浪女
悲&欢浪女 2020-12-04 17:41

Is there a way in Linq to do an OrderBy against a set of values (strings in this case) without knowing the order of the values?

Consider this data:

A         


        
8条回答
  •  醉话见心
    2020-12-04 18:21

    If you put your preferences into a list, it might become easier.

    List data = new List { "A","B","A","C","B","C","D","E" };
    List preferences = new List { "A","B","C" };
    
    IEnumerable orderedData = data.OrderBy(
       item => preferences.IndexOf(item));
    

    This will put all items not appearing in preferences in front because IndexOf() returns -1. An ad hoc work around might be reversing preferences and order the result descending. This becomes quite ugly, but works.

    IEnumerable orderedData = data.OrderByDescending(
       item => Enumerable.Reverse(preferences).ToList().IndexOf(item));
    

    The solution becomes a bit nicer if you concat preferences and data.

    IEnumerable orderedData = data.OrderBy(
       item => preferences.Concat(data).ToList().IndexOf(item));
    

    I don't like Concat() and ToList() in there. But for the moment I have no really good way around that. I am looking for a nice trick to turn the -1 of the first example into a big number.

提交回复
热议问题