簡體   English   中英

LINQ OrderBy 自定義訂單

[英]LINQ OrderBy custom order

假設我有以下字符數組:

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

我自己的解決方案(感謝那些引導我走向正確方向的人)

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

產生:

CCCCDDDDDDRRRRRRRRRRRGGGGGG

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

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

如果要將訂單定義為項目之間的關系,則必須將IComparer與其他OrderBy 方法一起使用

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

我會通過連接來解決這個問題,確保排序數組位於連接的左側。

var ordering = "CDGR".ToCharArray();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM