19

We have a generic List(Of Product) that must be sorted on two or more properties of the Product class.

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.

How can it be sort with a Lamba statement? If you have found to sort the list based on one property.

5 Answers 5

40

EDIT Just realized this was a VB question. Here is the VB.Net solution

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

var list = GetSomeList(); var sorted = list.OrderBy(x => x.Popular).ThenBy(x => x.Clicked).ThenBy(x => x.Name); 
Sign up to request clarification or add additional context in comments.

Comments

7

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.

For a non-LINQ solution:

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) 

4 Comments

Solved a problem I had. Thanks!
@Guffa -- VB does support multiline lambda expressions.
@roryap: Yes, it does now. Not when the answer was written.
@Guffa It's really helpful when you bound not to use LINQ, thanks you saved me.
5
List<Product> sortedProducts = null; sortedProducts = products.OrderBy(p => p.Popular) .ThenByDescending(p => p.Clicked) .ThenBy(p => p.Name) .ToList(); 

Comments

4

I'm sorry but do you know any C#?

products.OrderBy(p => p.Popular). ThenByDescending(p => p.Clicked). ThenBy(p => p.Name); 

Can you get what you need from this?

1 Comment

brilliant! I didn't know about the "ThenBy"
0

A compound sort can also be done with the List.Sort lambda function. Here is a vb.Net example:

 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) 

Comments