c# List< string>排序问题
本文关键字:排序 问题 string List | 更新日期: 2023-09-27 18:14:25
我有一个列表看起来像:
List<string> newList = new List<string>() { "10S", "XS", "80", "5S", "160", "40S", "80S", "STD", "40", "XXS" };
我想把它排序到
- {"40"、"80"、"160"、"5 s","10","40年代","80年代"、"性病","x","XXS"};
我该怎么做?希望有人能在这个问题上帮助我,非常感谢!
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"、"5 s","10","40年代","80年代"、"性病","x","XXS"};
我写了一些代码,它工作。我只是用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();
}
}
}