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 に答える