Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Algorithm - C#

Tags:

c#

sorting

linq

I have the following unsorted list:

List<string> myUnsortedList = New List<string>();

myUnsortedList.Add("Alpha");
myUnsortedList.Add("(avg) Alpha");
myUnsortedList.Add("Zeta");
myUnsortedList.Add("Beta");
myUnsortedList.Add("(avg) Beta");
myUnsortedList.Add("(avg) Zeta");

I want to sort the list descending alphabetical order, then have the value with (avg) right after the normal value:

Final Result: Zeta, (avg) Zeta, Beta, (avg) Beta, Alpha, (avg) Alpha

My application is written in C# and I want to use LINQ to accomplish the sorting

like image 406
Michael Kniskern Avatar asked Apr 25 '26 22:04

Michael Kniskern


1 Answers

This should work ok for what you need, assuming "(avg)" is the only special prefix

This will order all the stings descending not including the "(avg) " then it will order by the strings length this way the string with the "(avg)" prefix will come after the one without

var result = myUnsortedList.OrderByDescending(x => x.Replace("(avg) ", "")).ThenBy(x => x.Length);

Final Result:

  • Zeta
  • (avg) Zeta
  • Beta
  • (avg) Beta
  • Alpha
  • (avg) Alpha
like image 89
sa_ddam213 Avatar answered Apr 28 '26 12:04

sa_ddam213



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!