How can I create a sequence of string combinations of alphabet and number?
I have a list of data like:
List<String> Dummy = new List<String>()
{
"1001A",
"1003A",
"1002B",
"1002A",
"1003B",
"1001B",
"1003C",
"1002C",
"1001C",
};
I want to order this list of data in a row. The main series will focus on the alphabet (the last char of the string), and the sub-series will be based on the numbers on the left. The result will be like this:
1001A 1002A 1003A 1001B 1002B 1003B 1001C 1002C 1003C
I already have function codes for a number of numbers only, other than the above example. Thanks for reading my post.
source to share
If it is possible that the strings are of different lengths then the following will be required.
var result = data.OrderBy(d => d[d.Length - 1])
.ThenBy(d => int.Parse(d.Substring(0, d.Length - 1])));
Of course, you need to guard against possible parsing exceptions with bad data.
This assumes that you want "200A" to come before "1000A".
source to share
var result = Dummy
.OrderBy(p => p[p.Length - 1])
.ThenBy(p => p.Substring(0, p.Length - 1));
This will be ordered first by the last character of the string and then everything but the last character of the string.
If all lines are the same length, you can also leave the last part in .ThenBy(p => p)
, since the lines are already sorted by the last character. If the length of the strings is different, you need a substring as in my code.
source to share
version a) (fastest)
Use the built-in sort method (sorts in place), using the custom delegate / lambda
dummy.Sort((s1, s2) =>
{
// TODO: Handle null values, now supposing s1 and s2 are not null
// TODO: Handle variable length if needed. Supposing fixed 4+1 data
var result = s1[4].CompareTo(s2[4]);
if (result != 0)
{
return result;
}
return s1.Substring(0, 4).CompareTo(s2.Substring(0, 4));
});
To reuse the comparison, you can write it as a static method instead of the inline lambda, however in this case, I recommend using IComparator instead. (The sort method has an overload that accepts an IComparator)
version b):
Use LINQ:
// TODO: Handle variable length if needed, supposing fixed 4+1 data structure:
var orderedList = dummy.OrderBy(s => s[4]).ThenBy(s => s.SubString(0,4).ToList();
source to share