如何对列表列表进行排序?

编程入门 行业动态 更新时间:2024-10-10 01:20:25
本文介绍了如何对列表列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好的,我有一个列表要排序.首先,一些代码:

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.

更多推荐

如何对列表列表进行排序?

本文发布于:2023-11-29 08:59:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!