Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create series of string combination of Alphabet and Number?

Tags:

c#

I have a collection of data list for example:

List<String> Dummy = new List<String>()
{
  "1001A",
  "1003A",
  "1002B",
  "1002A",
  "1003B",
  "1001B",
  "1003C",
  "1002C",
  "1001C",
};

I want to arrange this data list into series. The main series will focus on the Alphabet(the last char of the string) and the sub series will be base on the numbers left. The output will like this:

1001A
1002A
1003A
1001B
1002B
1003B
1001C
1002C
1003C

I already have function codes only for the series of numbers except about the example above. Thanks for the reading my post.

like image 329
Bad Idea Avatar asked Aug 30 '25 18:08

Bad Idea


2 Answers

 var result = Dummy
              .OrderBy(p => p[p.Length - 1])
              .ThenBy(p => p.Substring(0, p.Length - 1));

This will first order by the last character of the string and then by everything except the last character of the string.

If all strings have the same length, you can also leave the last part at .ThenBy(p => p), as the strings are already sorted by the last character. If string lengths differ, you need the substring as in my code though.

like image 59
LInsoDeTeh Avatar answered Sep 02 '25 09:09

LInsoDeTeh


If it's possible for the strings to have different lengths then the following would be needed.

var result = data.OrderBy(d => d[d.Length - 1])
                 .ThenBy(d => int.Parse(d.Substring(0, d.Length - 1])));

You'd of course need to guard against possible parsing exceptions with bad data.

This assumes that you'd want "200A" to come before "1000A".

like image 33
juharr Avatar answered Sep 02 '25 07:09

juharr