-1

Why List<Component> l = second.ToList(); lead to

System.NullReferenceException' occurred in ConsoleApplication1.exe

in select new { id = b.id, Name = b.Name };

How to fix this?

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        List<Component> firstlist = new List<Component>();
        List<Component> secondlist = new List<Component>();
        List<Component> thirdlist = new List<Component>();

        firstlist.Add(new Component { id = 1, Name = "Jhon" });
        secondlist.Add(new Component { id = 2, Name = "Jhon" });
        thirdlist.Add(new Component { id = 3, Name = "Jhon" });

        var first = from d in firstlist
                                 join i in secondlist
                                 on d.id equals i.id
                                 into a
                                 from b in a.DefaultIfEmpty()
                                 select new { id = b.id, Name = b.Name };

        var second = from f in first
                     join s in thirdlist
                     on f.id equals s.id
                     into a
                     from b in a.DefaultIfEmpty()
                     select new Component { id = b.id, Name = b.Name };

        List<Component> l = second.ToList();

    }

    public class Component
    {
        public int id { get; set; }

        public string Name { get; set; }
    }
}
}
0

2 Answers 2

8

When you have the line:

from b in a.DefaultIfEmpty()

You're specifically saying that you should use a default value for items in that list if it's empty. The default value for reference types (which those anonymous objects are) is null, and you're dereferencing that value, so you get a NRE.

0

No equality between firstlist and secondlist, join cannot work ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.