Shantanu Gupta
Shantanu Gupta

Reputation: 21198

Do we have sorting and searching function in .net

I was implementing linear search for search in a collection then i thought why not use 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.

Upvotes: 2

Views: 324

Answers (3)

Johnny
Johnny

Reputation: 1575

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));

Upvotes: 4

Oded
Oded

Reputation: 499042

From this SO answer:

.NET uses a variation of Quicksort (Sedgewick's median of 3 Quicksort).

Upvotes: 3

Matt Mitchell
Matt Mitchell

Reputation: 41823

.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.

Upvotes: 2

Related Questions