[英]Linq ToList strange behaviour
为什么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; }
}
}
}
当您有一行时:
from b in a.DefaultIfEmpty()
您是专门说如果列表中的项目为空,则应使用默认值。 引用类型(那些匿名对象是)的默认值是null
,并且您正在取消引用该值,因此得到一个NRE。
第一列表和第二列表之间没有相等关系,联接无法工作;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.