Do we have sorting and searching function in .net
I was implementing linear search for search in a collection then i thought why not us开发者_开发百科e binary search, for which i had to use sorting. Although I can implement them, but I would like to know where does they exists in .net itself. I hope it would be present in .Net.
If I didn't get it wrong this is something you are looking for
public class Person
{
public int age;
public string name;
public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}
List<Person> people = new List<Person>();
people.Add(new Person(50, "Fred"));
people.Add(new Person(30, "John"));
people.Add(new Person(26, "Andrew"));
people.Add(new Person(24, "Xavier"));
people.Add(new Person(5, "Mark"));
people.Add(new Person(6, "Cameron"));
For Searching
// with delegate
List<Person> young = people.FindAll(delegate(Person p) { return p.age < 25; });
// with lammda
List<Person> young = people.FindAll(a=> a.age < 25);
For Sorting
// with delegate
people.Sort(delegate(TestKlasse a, TestKlasse b) { return a.age.CompareTo(b.age); });
// with lambda function
people.Sort((a, b) => a.age.CompareTo(b.age));
From this SO answer:
.NET uses a variation of Quicksort (Sedgewick's median of 3 Quicksort).
.NET has sorting implemented by default, but while you can specify the order in which you would like your elements sorted, you cannot specify the algorithm with which it sorts.
As such, you might be interested in this article which provides .NET code for abstractly sorting including implementations of every major sorting method.
精彩评论