C# List<string> 排序问题 [关闭]

Posted

技术标签:

【中文标题】C# List<string> 排序问题 [关闭]【英文标题】:C# List<string> sort issue [closed] 【发布时间】:2013-05-15 16:58:50 【问题描述】:

我的列表看起来像:

List<string> newList = new List<string>()  "10S", "XS", "80", "5S", "160", "40S", "80S", "STD", "40", "XXS" ;

我想把它排序到

“40”、“80”、“160”、“5S”、“10S”、“40S”、“80S”、“STD”、“XS”、“XXS”;

我该怎么做?希望有人能帮助我解决这个问题,非常感谢!

【问题讨论】:

***.com/questions/188141/… 的副本 您将不得不覆盖排序功能(编写您自己的)。我不认为默认排序会按照你想要的方式排序。 您需要定义一个比较函数,该函数返回一个值,指示您希望它们的顺序。预定义的比较都不适用于此。 是否有我看不到的特定排序规则?所以你想要一个 asc 数字排序,然后 asc 字母 + 数字,然后一个 asc 字母排序? 【参考方案1】:
List<string> list = new List<string>()  "10S", "XS", "80", "5S", "160", "40S", "80S", "STD", "40", "XXS" ;

// filter out numbers:
int temp;
var newList = (from item in list where int.TryParse(item, out temp) select item).ToList();

// sort by number and get back string:
newList = newList.Select(x => int.Parse(x)).OrderBy(x => x).Select(x => x.ToString()).ToList();

// sort the rest by string:
var second = list.Except(newList).OrderBy(x => x).ToList();

// Merge the two back together
newList.AddRange(second);

newList 现在将是:“40”、“80”、“160”、“5S”、“10S”、“40S”、“80S”、“STD”、“XS”、“XXS”;

【讨论】:

很好的解决方案。您甚至可以在过滤掉以下数字后立即进行排序: var newList = (from item in list where int.TryParse(item, out temp) select item).OrderBy(x=>int.Parse(x)).ToList ();但可能你在这里看到的教学价值比简洁更多。【参考方案2】:

我写了一些代码,它可以工作。我只是用 Linq 做你想做的事

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SortTest

    class Program
    
        static void Main(string[] args)
        
            //your objects
            List<string> newList = new List<string>()  "10S", "XS", "80", "5S", "160", "40S", "80S", "STD", "40", "XXS" ;

            //filter the stuff you want first, and then sort them from small to big
            var sQuery = newList.Where(p => p.EndsWith("s", StringComparison.CurrentCultureIgnoreCase)).OrderBy(p => p);
            var numQuery = newList.Where(p => Regex.IsMatch(p, "^[0-9]+$", RegexOptions.Singleline)).OrderBy(p => p);
            var otherQuery = newList.AsQueryable().Where(p => !sQuery.Contains(p) && !numQuery.Contains(p));

            //get the result, add the sorts
            List<string> resultList = new List<string>();
            resultList.AddRange(numQuery);
            resultList.AddRange(sQuery);
            resultList.AddRange(otherQuery);

            //print them out
            Console.Write(string.Join(",", resultList.ToArray()));

            Console.WriteLine();
            Console.ReadKey();
        
    

【讨论】:

以上是关于C# List<string> 排序问题 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

简单排序,C# 直接使用 List。

C#:对键为 List<object> 的字典进行排序

C# List结果集排序

C#中的字符串排序问题

C# List 随机排序

C# 将 List<string> 添加到 List<List<string>> 数组