为什么要List<Component> l = second.ToList();导致
System.NullReferenceException'发生在ConsoleApplication1.exe中
在 select new { id = b.id, Name = b.Name };
如何解决这个问题?
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; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你有这条线:
from b in a.DefaultIfEmpty()
Run Code Online (Sandbox Code Playgroud)
您明确地说,如果该列表中的项目为空,则应使用默认值.引用类型(这些匿名对象是)的默认值是null,并且您取消引用该值,因此您获得NRE.