如何使用List <string> .Sort?</string>按长度排序字符串

时间:2013-11-26 12:01:29

标签: c# .net sorting

我想按照长度

对字符串列表进行排序
var weasleys = new List<string>{"Bill", "Charlie", "Percy", "Fred", "George", "Ron", "Ginny"};

我知道如何使用OrderBy

weasleys.OrderBy(x => x.Length)

但我想知道如何处理List<T>.Sort。怎么样?

3 个答案:

答案 0 :(得分:5)

Sort(Comparison<T>) overload有一个Comparison<T>代表。有了它,您可以在相应的CompareTo值上使用Length方法:

weasleys.Sort((x, y) => x.Length.CompareTo(y.Length));

请注意,与LINQ OrderBy方法不同,如果您的意图是Sort将会就地更改weasleys列表。

答案 1 :(得分:0)

这应该这样做

var weasleys = new List<string>{"Bill", "Charlie", "Percy", "Fred", "George", "Ron", "Ginny"};
var t = weasleys.OrderBy(x => x.Length).ToList<string>();

答案 2 :(得分:0)

您可以使用Array List ...

执行此操作
public class SortStringLength : IComparer
    {
        public int Compare(Object s1, Object s2)
        {
            if (s1.ToString().Length == s2.ToString().Length)
                return String.CompareOrdinal(s1.ToString(), s2.ToString());
            if (s1.ToString().Length > s2.ToString().Length)
                return 1;
            return -1;
        }
    }

然后使用IComparer ...

static void Main(string[] args)
        {
            var weasleys = new ArrayList { "Bill", "Charlie", "Percy", 
                  "Fred", "George", "Ron", "Ginny" };
            var sortLength = new SortStringLength();
            weasleys.Sort(sortLength);

            foreach (var weasley in weasleys)
            {
                Console.WriteLine(weasley);
            }

            Console.ReadLine();
        }

使用List ...

public class SortStringLength : IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x.Length == y.Length)
            return String.CompareOrdinal(x, y);
        if (x.Length > y.Length)
            return 1;
        return -1;
    }
}

和用法......

static void Main(string[] args)
        {
            var weasleys = new List<string> { "Bill", "Charlie", "Percy", 
                       "Fred", "George", "Ron", "Ginny" };
            var sortLength = new SortStringLength();
            weasleys.Sort(sortLength);

            foreach (var weasley in weasleys)
            {
                Console.WriteLine(weasley);
            }

            Console.ReadLine();
        }