Good day
I have been trying to use a linq to entity SelectMany() but always throw "object reference not set to an instance of an object" exception. thougth may be one of the elements of the sequence was null. Therefore i try to extend(write an extension method) for the SelectMany() as SelectManyOrDefault() to check is there is any null element and skip such but i was still getting the same "object reference not set to an instance of an object" exception. Try to set break points debug my project but to my surprise none of the elements at any point is null or empty. The exception is been thrown on the "yeild return item". This is the extension method
- ///
- /// Projects each element of a sequence to an System.Collections.Generic.IEnumerable
- /// and flattens the resulting sequences into one sequence.
- /// Or returns a default value if the sequence contains no elements.
- /// A sequence of values to project.
- /// A transform function to apply to each element.
- ///
The type of the elements of source. - ///
The type of the elements of the sequence returned by selector. - ///
An System.Collections.Generic.IEnumerable`1 whose elements are the result of - /// invoking the one-to-many transform function on each element of the input sequence.
- ///
- /// System.ArgumentNullException:
- /// source or selector is null.
- ///
- ///
- public static IEnumerable
SelectManyOrDefault (this IEnumerable source, Func > selector) - {
- if (source == null)
- throw new ArgumentNullException("source");
- if (selector == null)
- throw new ArgumentNullException("selector");
- //if (source.Count() <= 0)
- //return default(IEnumerable
); - //if (source.Count() == 1)
- // return source.Select(selector).FirstOrDefault();
- foreach (TS element in source.DefaultIfEmpty())
- {
- if (element != null)
- {
- foreach (TR item in selector(element).DefaultIfEmpty())
- {
- if(item != null)
- yield return item;
- }
- }
- }
- //return result;
- }
Please help me, I don't know what is actually cause this exception.I have been on this for a week now.

Replies
Know the answer? Post it — somebody with the same question will find it here.