我想按照长度
对字符串列表进行排序var weasleys = new List<string>{"Bill", "Charlie", "Percy", "Fred", "George", "Ron", "Ginny"};
我知道如何使用OrderBy
。
weasleys.OrderBy(x => x.Length)
但我想知道如何处理List<T>.Sort
。怎么样?
答案 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();
}