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
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.
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.
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.
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);
}
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With