gpt4 book ai didi

c# - LINQ 加入 : Object reference not set to an instance of an object

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:24 25 4
gpt4 key购买 nike

我有一个从 Linq to SQL 生成的列表。为简单起见,它看起来像这样:

var myItems = (from my in db.MyTable
select new
{
UniqueID = my.ID,
UserName = my.UserName,
CreatedOn = my.CreatedOn
}).ToList();

此列表包含 4 个项目。

我还有一个:

var grid = (from q in AnotherLinqQuery
select new
{
UniqueID = q.ID,
Department = q.Department,
Comments = q.Comments
}).ToList();

此列表包含 20 个项目。myItems 中的所有 ID 都显示在网格中。

现在我想用左连接将它连接起来。

var q = from A in grid
from B in myItems.Where(x => x.UniqueID == grid.UniqueID).DefaultIfEmpty()
select new
{
UniqueID = A.UniqueID,
Department = A.Department,
CreatedOn = B.CreatedOn
}

当我执行这个时,我得到

Object reference not set to an instance of an object.

我也尝试过其他连接,例如

from A in grid
from B in myItems.Where(x => x.UniqueID != null && x.UniqueID == grid.UniqueID).DefaultIfEmpty()

最佳答案

您没有正确加入。试试这个:

var q = from A in grid
join B in myItems on A.UniqueId equals B.UniqueId into LB
from B in LB.DefaultIfEmpty()
select new
{
UniqueID = A.UniqueID,
Department = A.Department,
CreatedOn = B.CreatedOn
};

您可能需要引用 documentation有关加入 linq 的更多信息。

关于c# - LINQ 加入 : Object reference not set to an instance of an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38715735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com