Linq OrderBy against specific values

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

    Danbrucs solution is more elegant, but here is a solution using a custom IComparer. This might be useful if you need more advanced conditions for your sort ordering.

        string[] svals = new string[] {"A", "B", "A", "C", "B", "C", "D", "E"};
        List list = svals.OrderBy(a => a, new CustomComparer()).ToList();
    
        private class CustomComparer : IComparer
        {
            private string firstPref = "A";
            private string secondPref = "B";
            private string thirdPref = "C";
            public int Compare(string x, string y)
            {
                // first pref 
                if (y == firstPref && x == firstPref)
                    return 0;
                else if (x == firstPref && y != firstPref)
                    return -1;
                else if (y == firstPref && x != firstPref)
                    return 1;
                // second pref
                else if (y == secondPref && x == secondPref)
                    return 0;
                else if (x == secondPref && y != secondPref)
                    return -1;
                else if (y == secondPref && x != secondPref)
                    return 1;
                // third pref
                else if (y == thirdPref && x == thirdPref)
                    return 0;
                else if (x == thirdPref && y != thirdPref)
                    return -1;
                else
                    return string.Compare(x, y);
            }
        }
    

提交回复
热议问题