在两个或多个值上排序通用列表

18 .net vb.net sorting generics lambda

我们有一个通用List(Of Product),必须在Product类的两个或多个属性上进行排序.

产品类具有属性"Popular"数字(asc),"Clicked"数字(desc),"Name"字符串(asc).为了命名属性,我们希望列表进行排序.

如何用lamba语句排序?如果找到基于一个属性对列表进行排序.

Jar*_*Par 37

编辑刚刚意识到这是一个VB问题.这是VB.Net解决方案

Dim list = GetSomeList()
Dim sorted = list. _
  OrderBy(Function(x) x.Popular). _
  ThenBy(Function(x) x.Clicked). _
  ThenBy(Function(x) x.Name)
Run Code Online (Sandbox Code Playgroud)

C#版本.请尝试以下方法

var list = GetSomeList();
var sorted = list.OrderBy(x => x.Popular).ThenBy(x => x.Clicked).ThenBy(x => x.Name);
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 5

要回答关于lambda表达式的问题,这太复杂了,无法放入lambda表达式,因为VB不支持多行lambda表达式.

对于非LINQ解决方案:

您需要一个命名方法作为比较器:

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
Run Code Online (Sandbox Code Playgroud)

用法:

theList.Sort(AddressOf Comparer)
Run Code Online (Sandbox Code Playgroud)


und*_*ore 5

List<Product> sortedProducts = null;
sortedProducts = products.OrderBy(p => p.Popular)
                         .ThenByDescending(p => p.Clicked)
                         .ThenBy(p => p.Name)
                         .ToList();
Run Code Online (Sandbox Code Playgroud)


bru*_*nde 4

抱歉,你懂 C# 吗?

products.OrderBy(p => p.Popular).
    ThenByDescending(p => p.Clicked).
    ThenBy(p => p.Name);
Run Code Online (Sandbox Code Playgroud)

你能从中得到你需要的东西吗?