generic list Take not working?

it seems that generic list Take is not working in unity, can anyone confirm this?

It can be used to truncate

var itemsOneThroughTwenty = myList.Take(20);
var itemsFiveThroughTwenty = myList.Skip(5).Take(15);

if so, only certain elements of generic list are implemented?
I can still do this :

myList.GetRange(0, 20);

Jesus, mary, and the seven sexless angels bless you. I've wasted FOUR F-U-C-K-I-N-G hours on this, and now it works.

2 Answers

2

This works in my Unity 4.0:

    // C#
    var L = new List<int>();
    for (int i = 0; i < 30; i++)
        L.Add(i);
    foreach(var val in L.Skip(2).Take(5))
        Debug.Log(val);

This prints :

2
3
4
5
6

Are you sure you have a “using System.Linq;” in your script?
(and of course “using System.Collections.Generic;”)
Skip / Take and a lot of other functions are Linq extention methods which work on generic IEnumerable. Those functions are not part of the List class, they can be used on any generic collection but only when you “import” them.

edit
Even when they don’t exist they are not really hard to implement :wink:

public static IEnumerable<T> Take<T>(this IEnumerable<T> aSource, int aCount)
{
    foreach(T val in aSource)
    {
       if (aCount >0)
           yield return val;
       else
           yield break;
       aCount--;
    }
}

public static IEnumerable<T> Skip<T>(this IEnumerable<T> aSource, int aCount)
{
    foreach(T val in aSource)
    {
       if (aCount > 0)
       {
           aCount--;
           continue;
       }
       else
           yield return val;
    }
}

Haven’t testet it, but it should work :wink: That’s the whole magic.

They exist in Unity - presuming Linq is imported. Perhaps not directly on List.

I believe Take came in with .NET 3.5 - and if I recall correctly Unity is only using .NET 2.