2

我有一个列表,如下所示:

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”};

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

4

2 回答 2

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”};

于 2013-05-21T02:59:34.240 回答
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();
        }
    }
}
于 2013-05-21T02:54:28.270 回答