Reputation: 146
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.
Upvotes: 4
Views: 295
Reputation: 11228
A solution based on grouping:
var res = Dummy.GroupBy(str => str.Last()).OrderBy(g => g.Key)
.SelectMany(g => g.OrderBy(str => str.Substring(0, str.Length - 1)))
.ToList();
Upvotes: 1
Reputation: 35843
version a) (fastest)
Use built in Sort method (sorts in place), with a custom Comparision 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 Comparision you can write it as a static method instead of an inline lambda, however this case I recommend to implement an IComparator instead. (Sort method has an overload which accepts 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();
Upvotes: 1
Reputation: 32266
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".
Upvotes: 2
Reputation: 1038
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.
Upvotes: 7