0

I am using the following extension method (from an existing StackOverflow question) to split an existing enumerable into two:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
    int i = 0;
    var splits = from item in list
                 group item by i++ % parts into part
                 select part.AsEnumerable();
    return splits;
}

I am using the method like so:

//accountIds is simply an IEnumerable<string>
var foo = accountIds.Split(2).ToList();

The method seemingly works fine when I run my application. However, when I debug my application this line of code always throws an exception:

Object reference not set to an instance of an object.

I am very confused why this method only throws an exception when I am debugging.

Community
  • 1
  • 1
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • 1
    Mutating a variable inside a query is a worst practice. Don't do this in the first place. Why it is crashing I don't know but there are better ways to split a sequence. – Eric Lippert Feb 27 '13 at 03:10
  • did you look on your `foo` if it has any elements inside it? – Freddie Fabregas Feb 27 '13 at 03:11
  • @FreddieFabregas - If I remove the `.ToList()` call I avoid the exception and I am returned two enumerables each with ~1300 elements. – Justin Helgerson Feb 27 '13 at 03:14
  • Have you tried to narrow down the issue at all and isolating it away from your current project? I created the same thing and had no issue, but I don't know what exactly accountIds looks like, so I can only guess. – corylulu Feb 27 '13 at 03:26
  • @Corylulu - Yes. I should have been more specific, but, `accountIds` is nothing more than a list of strings. My real project example is pretty simple. – Justin Helgerson Feb 27 '13 at 03:27
  • @Ek0nomik Okay, well I have no problem stepping through this in debugger: http://pastie.org/6345471 Is this a fair representation of your code? – corylulu Feb 27 '13 at 03:35

1 Answers1

0

I'm not sure about this, but I think you should evaluate it first. You can use .ToArray() or .ToList() method.

Have a look on Jon Skeet blog on captured variables.

Freddie Fabregas
  • 1,162
  • 1
  • 7
  • 17