Linq OrderBy自定义订单

假设我有以下char数组:

char[] c = new char[] { 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C', 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C' }; c.OrderBy(y => y).ForEach(x => Console.WriteLine(x)); //CCCCDDDDDDGGGGGGRRRRRRRRRR 

如何使用linq生成以下订单?

 //DDDDDDGGGGGGRRRRRRRRRRCCCC 

可能你想做这样的事情:

 char [] customOrder = { 'D', 'G', 'R', 'C'}; char [] c = new char[] { 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C', 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C' }; foreach (char item in c.OrderBy(ch => Array.IndexOf(customOrder, ch))) { Console.Write(item); } 

您可以使用另一个定义顺序的集合:

 char[] order = {'D','G','R','C'}; var customOrder = c.OrderBy(chr => { int index = Array.IndexOf(order, chr); if (index == -1) return int.MaxValue; return index; }); 

我将通过连接来确保排序数组位于连接的左侧。

 var ordering = "CDGR".ToCharArray(); var orderedOutput = ordering.Join(c, a => a, b => b, (a, b) => b); 

我自己的解决方案(感谢那些带领我朝着正确方向前进的人)

 char[] c = new char[] { 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C', 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C' }; c.OrderBy(x => "CDRG".IndexOf(x)).ForEach(Console.Write); 

生产:

CCCCDDDDDDRRRRRRRRRRGGGGGG

您可以使用具有元素顺序的字典:

 Dictionary order = new Dictionary { { 'D', 0 }, { 'G', 1 }, { 'R', 2 }, { 'C', 3 }, }; char[] c = new char[] { 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C', 'G', 'R', 'D', 'D', 'G', 'R', 'R', 'C', 'D', 'G', 'R', 'R', 'C' }; // Here we search the dictionary for the "order" to be used // and we compare the value with the value of the other // compared item Array.Sort(c, (p, q) => order[p].CompareTo(order[q])); var str = new string(c); Console.WriteLine(str); 

如果要将订单定义为项之间的关系,则必须将IComparer与其他OrderBy方法一起使用 。

 public class Comparer : IComparer { public int Compare(Char a, Char b) { //return positive if a should be higher, return negative if b should be higher } } c.OrderBy(c => c, new Comparer()).ForEach(x => Console.WriteLine(x));