好的,我有一个列表,我想排序.首先,一些代码:
foreach (var Row in Result)
{
foreach (var RowAll in Row.All)
{
DataObject.Add(new List<string>() { RowAll.Value1, RowAll.Value2, RowAll.Value3});
break;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想按每个子列表的Value2对父列表进行排序.这可能吗?如果是这样,我该怎么做?
Ree*_*sey 13
您可以通过LINQ执行此操作:
// I'm assuming here that "LastCheckin" is defined as List<List<string>> or similar
// ...
var sorted = Data.LastCheckin.OrderBy(list => list[1]);
Run Code Online (Sandbox Code Playgroud)
这将返回IEnumerable<List<string>>
包含按子列表中的第二个值(Value2)排序的"列表".
如果要对列表进行排序,可以使用List<T>.Sort
:
Data.LastCheckin.Sort( (a,b) => a[1].CompareTo(b[1]) );
Run Code Online (Sandbox Code Playgroud)
如果需要在运行时指定升序或降序,一种简单的方法是:
bool ascending = true; // Set to false for decending
int mult = ascending ? 1 : -1;
Data.LastCheckin.Sort( (a,b) => mult * a[1].CompareTo(b[1]) );
Run Code Online (Sandbox Code Playgroud)
为了处理更复杂的检查,您可以将lambda分成多行:
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;
});
Run Code Online (Sandbox Code Playgroud)
这会处理a和b上的解析器失败,并应将它们放在排序的末尾.