-2

I've been looking everywhere for some examples on how could some methods used in LINQ be replaced with standard c# code. I have a very simple helper which I need to use in .NET 2.0 environment. I need an alternative for:

Skip()
Take()
using()

methods. I've seen this post, and seen LINQBridge solution, but was wondering if there is any resource that explains how to replace those methods with straight code alternative?

Community
  • 1
  • 1
Bartosz
  • 4,542
  • 11
  • 43
  • 69

1 Answers1

1

You could just write your own Take and Skip

public static IEnumerable<T> Skip<T>(IEnumerable<T> set, int count)
{
    if(set == null) throw ArgumentNullException("set");
    if(count < 0) throw ArgumentOutOfRangeException("count");
    return SkipImp(set, count);
}

private static IEnumerable<T> SkipImp<T>(IEnumerable<T> set, int count)
{
    foreach(var item in set)
    {
        if(count-- <= 0)
        {
            yield return item;
        }
    }
}

public static IEnumerable<T> Take<T>(IEnumerable<T> set, int count)
{
    if(set == null) throw ArgumentNullException("set");
    if(count < 0) throw ArgumentOutOfRangeException("count");
    return TakeImp(set, count);
}

private static IEnumerable<T> TakeImp<T>(IEnumerable<T> set, int count)
{
    foreach(var item in set)
    {
        if(count-- > 0)
        {
            yield return item;
        }
        else
        {
            yield break;
        }
    }
}

You'd have to do

var results = ContainingClass.Take(ContainingClass.Skip(list, 3), 4);

instead of

var results = list.Skip(3).Take(4);

Note the reason for two separate methods in each case is so the exceptions will be thrown when the method is called rather than when the IEnumerable<T> is iterated.

I think you can even make them extension methods if you use a compiler that supports that (VS 2008 and up), as it's a feature of the compiler version and not the .net version.

juharr
  • 31,741
  • 4
  • 58
  • 93