I need to sort the List by the numbers in the string while keeping the name with the string. Here is an example of what I have in mind:
An unordered List:
BA05
R01
BA03
MTA008
MTA002
R07
Ordered List:
R01
MTA002
BA03
BA05
R07
MTA008
I need to sort the List by the numbers in the string while keeping the name with the string. Here is an example of what I have in mind:
An unordered List:
BA05
R01
BA03
MTA008
MTA002
R07
Ordered List:
R01
MTA002
BA03
BA05
R07
MTA008
var unorderedList = new List<string>(){"BA05", "R01", "BA03", "MTA008", "MTA002", "R07"};
var orderedList = unorderedList
.Select(input => new
{
text = input,
number = int.Parse(Regex.Match(input, @"\d+").Value)
})
.OrderBy(x => x.number)
.Select(x => x.text).ToList();
/*
So you can do this:
- Create another list for the numbers that are in the strings
- Take the numbers out of the strings using .Substring(int startindex, int length), and add them to the number-list
- Perform a simple sorting algorithm by the number-list and exchange the elements in both lists with the same index
*/
List<string> strings = new List<string>();
List<int> numbers = new List<int>(); //Create a list for the numbers from the strings
//not important
FileStream FS = new FileStream("list.txt", FileMode.Open, FileAccess.Read);
StreamReader SR = new StreamReader(FS);
while(!SR.EndOfStream) { strings.Add(SR.ReadLine()); }
//not important
foreach (string s in strings)
{
int index = 0, result = 0;
do //Take the numbers out from the string (BA05 --> 05 --> (convert to int) 5)
{
int.TryParse(s.Substring(index, s.Length - index), out result);
if (result == 0) index++;
}
while (result == 0);
numbers.Add(int.Parse(s.Substring(index, s.Length - index)));
}
Console.WriteLine("Unsorted:");
foreach (string s in strings) Console.WriteLine(s);
//Perform a simple sorting algorithm (f.e.: a bubble sort)
for (int i = 1; i < numbers.Count; i++)
{
for (int j = 0; j < numbers.Count - 1; j++)
{
if (numbers[j] > numbers[j + 1]) //Exchange both elements with the same index in both list
{
int tempInt = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = tempInt;
string tempStr = strings[j];
strings[j] = strings[j + 1];
strings[j + 1] = tempStr;
}
}
}
Console.WriteLine("\nSorted:");
foreach (string s in strings) Console.WriteLine(s);
Output:
Unsorted: BA05 R01 BA03 MTA008 MTA002 R07
Sorted: R01 MTA002 BA03 BA05 R07 MTA008