You seem to be deliberately left aligning index your numbers, which will mean that the ascending string sorted sequence of 1 through 12 would would be 1, 11, 12, 2, 3, 4, ..
.
Since you have the index value during the creation of the string, it would be wasteful to again parse the number out of the string in order to sort it. It would be better to retain the index and the string separately in a suitable data structure, sort by the index, and then project out just the string.
Updated for OP's new Question
Creating a custom POCO class (with or without an IComparable
implementation) seems overkill everytime you need to sort an enumerable of related data by one of its properties.
Instead, you can easily build up a sortable anon class, struct or tuple containing the sortable integer and the concatenated string, then sort, then project out just the string. Either way, OP's GetPropertyValue
method appears to return (reflect) a weak type such as object
or string
- accepted answer wouldn't compile as it needs to cast index to an int
.
Here's value tuple solution:
var tuples = new List<(int index, string str)>();
foreach (ManagementObject disk in objectSearcher.Get() )
{
var indexValue = int.Parse(disk.GetPropertyValue("Index"));
tuples.Add((indexValue, string.Format("{0, -15} {1,-35} {2, -20}",
indexValue,
disk.GetPropertyValue("Model"),
diskSize)));
}
// Sort by index, and project out the assembled string.
var myList = tuples
.OrderBy(t => t.index)
.Select(t => t.str)
.ToList();
Original Answer, OP had a simple loop
What I've done below is to keep a Value tuple of the original string, and the parsed integer value of the first 15 digits.
Note that this will break if there are non-numeric characters in the first 15 characters of your string.
// Test Data
var strings = Enumerable.Range(0, 12)
.Select(i => (string.Format("{0, -15} {1,-35} {2, -20}", i, "Model", "35GB")));
// Project out a tuple of (index, string)
var indexedTuples = strings.Select(s => (idx: int.Parse(s.Substring(0, 15)), str: s));
var sorted = indexedTuples.OrderBy(t => t.idx)
.Select(t => t.str);