我有一个List看起来像:
List<string> newList = new List<string>() { "10S", "XS", "80", "5S", "160", "40S", "80S", "STD", "40", "XXS" };
我想把它分类到
我该怎么办?希望有人能帮助我解决这个问题,非常感谢!
答案 0 :(得分:2)
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”};
答案 1 :(得分:0)
我写了一些代码并且它有效。我只是用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();
}
}
}