TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Makinde A. Israel
1.6k
168
20.6k
Yield return throws object reference not set exception
Jun 12 2018 9:22 PM
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
/// <Summary>
/// Projects each element of a sequence to an System.Collections.Generic.IEnumerable<TResut>
/// and flattens the resulting sequences into one sequence.
/// Or returns a default value if the sequence contains no elements.
/// <param name="source">A sequence of values to project.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <typeparam name="TS">The type of the elements of source.</typeparam>
/// <typeparam name="TR">The type of the elements of the sequence returned by selector.</typeparam>
/// <returns>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.</returns>
/// <exceptions>
/// System.ArgumentNullException:
/// source or selector is null.
/// </exceptions>
/// </Summary>
public
static
IEnumerable<TR> SelectManyOrDefault<TS, TR>(
this
IEnumerable<TS> source, Func<TS, IEnumerable<TR>> selector)
{
if
(source ==
null
)
throw
new
ArgumentNullException(
"source"
);
if
(selector ==
null
)
throw
new
ArgumentNullException(
"selector"
);
//if (source.Count() <= 0)
//return default(IEnumerable<TR>);
//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.
Reply
Answers (
0
)
Modify entity afrer InsertOnSubmit
Left Outer Join Using Linq