.net 对两个或多个值的通用列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/869438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Generic list on two or more values
提问by JaredPar
We have a generic List(Of Product) that must be sorted on two or more properties of the Product class.
我们有一个通用的 List(Of Product),它必须按 Product 类的两个或多个属性进行排序。
The product class has the properties "Popular" numeric (asc), "Clicked" numeric (desc), "Name" string (asc). In order of naming the properties, we want the list to sort.
产品类具有属性“流行”数字(asc)、“点击”数字(desc)、“名称”字符串(asc)。为了命名属性,我们希望列表进行排序。
How can it be sort with a Lamba statement? If you have found to sort the list based on one property.
如何使用 Lamba 语句对其进行排序?如果您发现根据一个属性对列表进行排序。
回答by JaredPar
EDITJust realized this was a VB question. Here is the VB.Net solution
编辑刚刚意识到这是一个 VB 问题。这是VB.Net的解决方案
Dim list = GetSomeList()
Dim sorted = list. _
OrderBy(Function(x) x.Popular). _
ThenBy(Function(x) x.Clicked). _
ThenBy(Function(x) x.Name)
C# version. Try the following
C# 版本。尝试以下
var list = GetSomeList();
var sorted = list.OrderBy(x => x.Popular).ThenBy(x => x.Clicked).ThenBy(x => x.Name);
回答by Guffa
To answer your question about a lambda expression, that is too complex to put in a lambda expression, as VB doesn't support multi-line lambda expressions.
要回答有关 lambda 表达式的问题,由于 VB 不支持多行 lambda 表达式,因此无法放入 lambda 表达式中。
For a non-LINQ solution:
对于非 LINQ 解决方案:
You need a named method as a comparer:
您需要一个命名方法作为比较器:
Private Function Comparer(ByVal x As Product, ByVal y As Product) As Integer
Dim result As Integer = x.Popular.CompareTo(y.Popular)
If result = 0 Then
result = x.Clicked.CompareTo(y.Clicked)
If result = 0 Then
result = x.Name.CompareTo(y.Name)
End If
End If
Return result
End Function
Usage:
用法:
theList.Sort(AddressOf Comparer)
回答by underscore
List<Product> sortedProducts = null;
sortedProducts = products.OrderBy(p => p.Popular)
.ThenByDescending(p => p.Clicked)
.ThenBy(p => p.Name)
.ToList();
回答by bruno conde
I'm sorry but do you know any C#?
抱歉,您知道 C# 吗?
products.OrderBy(p => p.Popular).
ThenByDescending(p => p.Clicked).
ThenBy(p => p.Name);
Can you get what you need from this?
你能从中得到你需要的吗?
回答by Call Center Developer
A compound sort can also be done with the List.Sort lambda function. Here is a vb.Net example:
也可以使用 List.Sort lambda 函数完成复合排序。这是一个 vb.Net 示例:
Dim Conts As List(of clsContact)
Conts.Sort(Function(C1 As clsContact, C2 As clsContact)
Dim CompRes As Integer = C1.Contact_LastName.CompareTo(C2.Contact_LastName)
If CompRes = 0 Then
CompRes = C1.Contact_FirstName.CompareTo(C2.Contact_FirstName)
End If
Return CompRes
End Function)

