Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How sort a System.Collections.Generic.List in VB.Net?

I using a genric list(m_equipmentList ) which is collection of objects (Schedule_Payitem).
How can sort list according to a proerty of child object ?

Dim m_equipmentList As New List(Of Schedule_Payitem) 

Need to sort m_equipmentList on basis of resourceid property of Schedule_Payitem.

like image 302
Nakul Chaudhary Avatar asked Jan 13 '09 11:01

Nakul Chaudhary


People also ask

What is using System collections generic?

Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

How do I sort a list of names in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.

How does C# list sort work?

C# is using a default comparer method to sort integers numerically. The Sort method orders the integers in ascending order, while the Reverse method in descending order. The following example sorts integers with LINQ. In LINQ, we can choose between the query syntax or the method syntax.


Video Answer


2 Answers

Are you using VB9? If so, I'd use a lambda expression to create a Comparer(Of Schedule_PayItem). Otherwise, write a short class to implement IComparer(Of Schedule_PayItem). pass whichever one you've got into List.Sort.

An example for the lambda expression (untested):

m_equipmentList.Sort(Function(p1, p2) p1.ResourceID.CompareTo(p2.ResourceID)) 

And for the IComparer(Of Schedule_PayItem):

Public Class PayItemResourceComparer     Implements IComparer(Of Schedule_PayItem)     Public Function Compare(ByVal p1 As Schedule_PayItem, _                             ByVal p2 As Schedule_PayItem) As Integer         Return p1.ResourceID.CompareTo(p2.ResourceID)     End Function End Class  ...  m_equipmentList.Sort(New PayItemResourceComparer) 
like image 74
Jon Skeet Avatar answered Sep 21 '22 21:09

Jon Skeet


I don't know vb.net so I did it in C#

m_equipmentList.Sort(    (payItem1,payItem2)=>payItem1.ResourceID.CompareTo(payItem2.ResourceID)); 

and using the reflector translated it to vb.net hope it helps

m_equipmentList.Sort( Function (ByVal payItem1 As Schedule_Payitem, ByVal payItem2 As Schedule_Payitem)      Return payItem1.ResourceID.CompareTo(payItem2.ResourceID) End Function) 

or you can inherit Schedule_Payitem from IComparable and implement CompareTo and then just call m_equipmentList.Sort()

like image 23
Pablo Retyk Avatar answered Sep 21 '22 21:09

Pablo Retyk