0

I am trying to do, get randomly one of "list of objects" from all lists. I am getting NullReferenceException I also tried List couldn't make it work.

List<BL.Test.Test> Tests = BL.Test.GET.TestGroup(CategoryId);

// NullReferenceException on the line below:
int[] Groups = Tests.Select(d => d.TestGroupId).Distinct().ToArray(); 

Session["TestGroup"] = Tests.Select(t => t.TestGroupId = Groups[rnd.Next(Groups.Length)]);

Tests not null

6
  • 2
    Use the debugger to figure out what is null. Commented Dec 25, 2013 at 16:37
  • 1
    Can you please provide us the "Test" class and the return value of the "TestGroup" method? Commented Dec 25, 2013 at 16:39
  • I cant use debugger in lambda Commented Dec 25, 2013 at 16:50
  • 1
    Please check what Tests.Select(d => d.TestGroupId) returns. Commented Dec 25, 2013 at 16:56
  • The property get accessor for TestGroupId throws an exception. This is an example why it is confusing when get accessors throw; they should not. Commented Dec 25, 2013 at 16:58

2 Answers 2

2

Obviously, BL.Test.GET.TestGroup is the method which returns null.

That's the most probable explanation for a NullReferenceException in a second line of your example.

And if Select, Distinct and ToArray are extension methods declared in System.Linq, this reason is the only possible, so check your method.

UPD.

Sorry guys, I am wrong.

TestGroupId member of BL.Test.Test class is missed.

UPD-2

This is a good example of community debugging question. As I know it is not appreciated here

Sign up to request clarification or add additional context in comments.

1 Comment

How did you checked that?
0

Since TestGroupId would be null hence null.Distinct() throws NullArgumentReference exception. Change ur code with following code:

List<BL.Test.Test> Tests = BL.Test.GET.TestGroup(CategoryId);

int[] Groups = Tests.Where(d=>d.TestGroupId.HasValue).Select(d => d.TestGroupId).Distinct().ToArray(); 

Session["TestGroup"] = Tests.Select(t => t.TestGroupId = Groups[rnd.Next(Groups.Length)]);

Make use of HasValue to find if TestGroupId has some value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.