Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ OrderBy custom order

Tags:

c#

linq

Say I have the following character array:

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

How do I use LINQ to produce the following order?

//DDDDDDGGGGGGRRRRRRRRRRCCCC
like image 661
Matthew Layton Avatar asked Feb 26 '15 12:02

Matthew Layton


People also ask

Is LINQ OrderBy stable?

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.

What is OrderBy in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

How to sort in descending order in LINQ?

OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.


2 Answers

Maybe you want to do something like this:

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);
}
like image 72
Perfect28 Avatar answered Nov 20 '22 00:11

Perfect28


You could use another collection which defines the order:

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;
});
like image 41
Tim Schmelter Avatar answered Nov 20 '22 01:11

Tim Schmelter