Linq OrderBy against specific values

后端 未结 8 1738
悲&欢浪女
悲&欢浪女 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:12

    In addition to @Daniel Brückner answer and problem defined at the end of it:

    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.

    I think that the solution is to use a statement lambda instead of an expression lambda.

    var data = new List { "corge", "baz", "foo", "bar", "qux", "quux" };
    var fixedOrder = new List { "foo", "bar", "baz" };
    data.OrderBy(d => {
                        var index = fixedOrder.IndexOf(d);
                        return index == -1 ? int.MaxValue : index; 
                      });
    

    The ordered data is:

    foo 
    bar 
    baz 
    corge 
    qux 
    quux 
    

提交回复
热议问题