Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Linq OrderBy method?

Tags:

c#

linq

I am trying to understand more about linq, for example, if I want to implement a Select I will implement like this

public static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
    foreach (var item in source)
    {
        yield return selector(item);
    }
}

where like this

public static IEnumerable<TSource> Where<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    foreach (var item in source)
    {
        if (predicate(item))
            yield return item;
    }
}

How about OrderBy?

like image 583
Larry Avatar asked Oct 26 '12 00:10

Larry


2 Answers

Take a look at this. I think you'll find it very useful. Basically, Jon Skeet re-implements everything in Linq as a learning exercise. Very informative.

The second part talks about implementing Where... and so on till parts that describes OrderBy.

like image 55
Randy Minder Avatar answered Oct 16 '22 18:10

Randy Minder


To follow you current implementation pattern you could try this:

public static IEnumerable<TSource> OrderBy<TSource, TKey>(
    IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    var items = source.ToArray();
    var keys = items.Select(keySelector).ToArray();
    Array.Sort(keys, items);
    foreach (var item in items)
    {
        yield return item;
    }
}
like image 22
Enigmativity Avatar answered Oct 16 '22 18:10

Enigmativity