如何对列表列表进行排序? [英] How To Sort A List Of Lists?
问题描述
好的,我有一个列表要排序.首先,一些代码:
Ok, I have a list of lists that I would like to sort. First, some code:
foreach (var Row in Result)
{
foreach (var RowAll in Row.All)
{
DataObject.Add(new List<string>() { RowAll.Value1, RowAll.Value2, RowAll.Value3});
break;
}
}
现在,我想按每个子列表的Value2对父列表进行排序. 这可能吗?如果是这样,我该怎么办?
Now I want to sort the parent list by each child list's Value2. Is this possible? If so, how can I do this?
推荐答案
您可以通过LINQ执行此操作:
You can do this via LINQ:
// I'm assuming here that "LastCheckin" is defined as List<List<string>> or similar
// ...
var sorted = Data.LastCheckin.OrderBy(list => list[1]);
这将返回一个IEnumerable<List<string>>
,其中包含按子列表(Value2)中第二个值排序的列表".
This will return an IEnumerable<List<string>>
containing your "lists" sorted by the second value in the sub-list (Value2).
如果要对列表进行排序,可以使用 List<T>.Sort
代替:
If you want to sort the list in place, you could use List<T>.Sort
instead:
Data.LastCheckin.Sort( (a,b) => a[1].CompareTo(b[1]) );
如果您需要在运行时指定升序或降序,则一种简单的处理方法是:
If you need to specify, at runtime, ascending or decending, an easy way to handle this is:
bool ascending = true; // Set to false for decending
int mult = ascending ? 1 : -1;
Data.LastCheckin.Sort( (a,b) => mult * a[1].CompareTo(b[1]) );
为了处理更复杂的检查,您可以将lambda分成多行:
In order to handle more complex checking, you can split your lambda over multiple lines:
bool ascending = true; // Set to false for decending
string myDateFormat = GetDateFormat(); // Specify date format
int mult = ascending ? 1 : -1;
Data.LastCheckin.Sort( (aStr,bStr) =>
{
DateTime a, b;
bool aSuccess = DateTime.TryParseExact(aStr[1], myDateFormat, DateTimeStyles.None, CultureInfo.InvariantCulture, out a);
bool bSuccess = DateTime.TryParseExact(bStr[1], myDateFormat, DateTimeStyles.None, CultureInfo.InvariantCulture, out b);
int result;
if (!aSuccess)
result = bSuccess ? -1 : 0;
else if (!bSuccess)
result = 1;
else
result = a.CompareTo(b);
return mult * result;
});
这处理了a和b上的解析器故障,应将它们放在排序的末尾.
This handles parser failures on a and b, and should put them at the end of the sort.
这篇关于如何对列表列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!