mohsinali1317
mohsinali1317

Reputation: 4425

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

Upvotes: 3

Views: 113

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

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

Upvotes: 4

Related Questions