Reputation: 6572
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)]);
Upvotes: 0
Views: 143
Reputation: 3834
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.
Upvotes: 0
Reputation: 9498
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
Upvotes: 2