Linq OrderBy自定义订单

时间:2015-02-26 12:30:12

标签: c# linq

说我有以下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

6 个答案:

答案 0 :(得分:15)

可能你想做这样的事情:

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); 
}

答案 1 :(得分:3)

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

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;
});

答案 2 :(得分:1)

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

var ordering = "CDGR".ToCharArray();

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

您可以使用包含元素顺序的字典:

Dictionary<char, int> order = new Dictionary<char,int> {
    { '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);

答案 5 :(得分:0)

如果您想将订单定义为商品之间的关系,则必须将IComparer与其他OrderBy method一起使用。

public class Comparer : IComparer<char>
{
    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));
相关问题