简体   繁体   English

C# 对包含数字的字符串列表进行排序 2

[英]C# Sorting a list of strings that contains numbers 2

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: Output:

Unsorted: BA05 R01 BA03 MTA008 MTA002 R07未分类:BA05 R01 BA03 MTA008 MTA002 R07

Sorted: R01 MTA002 BA03 BA05 R07 MTA008排序:R01 MTA002 BA03 BA05 R07 MTA008

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM