Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# alphanumeric list sorting by checking if list item contains

I have a List<string> like this

List<string> Test_List = new List<string>()
{
    "ZZA-KG-TEST",
    "ZZA-EG-TEST",
    "ZZA-KL-10A",
    "ZZA-KL-5A",
    "ZZA-KL-1A",
    "ZZA-FG-TEST",
    "RO-ELEVER"
};

Expected output after sorting

List<string> Test_List = new List<string>()
{
    "ZZA-KL-1A",
    "ZZA-KL-5A",
    "ZZA-KL-10A",
    "ZZA-KG-TEST",
    "ZZA-FG-TEST",
    "ZZA-EG-TEST",
    "RO-ELEVER"
};

What I am actually getting is

List<string> Test_List = new List<string>()
{
    "ZZA-KL-1A",
    "ZZA-KL-5A",
    "ZZA-KL-10A",
    "RO-ELEVER"
    "ZZA-EG-TEST",
    "ZZA-FG-TEST",
    "ZZA-KG-TEST",
};

My code is this

var data = Test_List
    .OrderByDescending(i => i.Contains("-KL-"))
    .ThenBy(i => i, new AlphanumericComparer())
    .ThenByDescending(i => i.Contains("-KG-"))
    .ThenBy(i => i, new AlphanumericComparer())
    .ThenByDescending(i => i.Contains("-FG-"))
    .ThenBy(i => i, new AlphanumericComparer())
    .ThenByDescending(i => i.Contains("-EG-"))
    .ThenBy(i => i, new AlphanumericComparer());

class AlphanumericComparer : IComparer<string>
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    static extern int StrCmpLogicalW(string s1, string s2);

    public int Compare(string x, string y) => StrCmpLogicalW(x, y);
}

Any thoughts?

EDIT I need all items containing -KL- comes at top and then order them withing -KL- and same for -KG-, -FG- and -EG- and then the rest

like image 894
mohsinali1317 Avatar asked Dec 14 '25 15:12

mohsinali1317


1 Answers

You, probably, want first to order groups (KL, KG, FG, EG, all_the_rest in this very order):

.OrderByDescending(i => i.Contains("-KL-"))
.ThenByDescending(i => i.Contains("-KG-"))
.ThenByDescending(i => i.Contains("-FG-"))
.ThenByDescending(i => i.Contains("-EG-"))

And only then order items within each group:

.ThenBy(i => i, new AlphanumericComparer());

i.e.

var data = Test_List
  .OrderByDescending(i => i.Contains("-KL-"))
  .ThenByDescending(i => i.Contains("-KG-"))
  .ThenByDescending(i => i.Contains("-FG-"))
  .ThenByDescending(i => i.Contains("-EG-"))
  .ThenBy(i => i, new AlphanumericComparer());
like image 60
Dmitry Bychenko Avatar answered Dec 17 '25 05:12

Dmitry Bychenko



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!