Finding items on a generic list.  
Author Message
DagoFlores





PostPosted: Visual C# Language, Finding items on a generic list. Top

Hello, in a generic list, why I apply the sort() method first and then I can find a specific element of a generic list List<T>

Thanks,



Visual C#8  
 
 
James Curran





PostPosted: Visual C# Language, Finding items on a generic list. Top

It's unclear what you are asking for.

If your object implements IComaprable, List<T>.Sort will properly sort the list.

Finding an item depends on what you mean by "specific element".... By index number By a particular property



 
 
Paul Louth





PostPosted: Visual C# Language, Finding items on a generic list. Top

I assume you mean to do a BinarySearch   That's because the BinarySearch only works with a sorted list.  It works using the divide-and-conquer method.  ie.  it gets the middle value of the list, if the value you're looking for is less that that value then it must be in the first half of the list, if it's greater than then it must be in the second half.  It then repeats this until it finds what you're looking for.  Obviously if the list isn't sorted then the BinarySearch won't work.

You could alternatively use Dictionary<T> or Hashtable, which are far more efficient ways of finding an item in a collection from a key.  Then you do not need to sort before you do a 'search'.

 


 
 
DagoFlores





PostPosted: Visual C# Language, Finding items on a generic list. Top

Yes, that was what looked for. Because I create the list List<T> with elements of T type, then I try to obtain the index of a specific element using the BinarySearch() method with IComparer interface. All that without classifying the list first. By the way,
Thanks.