gpt4 book ai didi

c# - LINQ GroupBy 抛出错误

转载 作者:行者123 更新时间:2023-11-30 16:19:33 25 4
gpt4 key购买 nike

 var devSum = repository.Devices
.Where(dev => dev.Id == deviceId)
.Join(repository.ManagementGroups, device => device.ManagementGroupId, mGroup => mGroup.Id, (device, mGroup) => new { device, mGroup.Name })
.Join(repository.DataGroups, device_mGroup => device_mGroup.device.DataGroupId, dGroup => dGroup.Id, (device_mGroup, dGroup) => new { device_mGroup.device, managerName = device_mGroup.Name, dataName = dGroup.Name })
.Join(repository.DeviceTypes, d => d.device.TypeId, t => t.Id, (d, t) => new { d.device, d.dataName, d.managerName, TypeName = t.Name })
.SingleOrDefault();

您好,我将上述查询连接到多个表中,并且一切正常。然后我意识到一些外键可能是空的。

我研究了 GroupByDefaultIfEmpty 的使用,它们听起来很有希望,所以我尝试将第一个 Join 更改为 GroupJoin 打开,但这引发了错误:

 var devSum = repository.Devices
.Where(dev => dev.Id == deviceId)
.GroupJoin(repository.ManagementGroups, device => device.ManagementGroupId, mGroup => mGroup.Id, (device, mGroup) => new { device, mGroup.Name })
.Join(repository.DataGroups, device_mGroup => device_mGroup.device.DataGroupId, dGroup => dGroup.Id, (device_mGroup, dGroup) => new { device_mGroup.device, managerName = device_mGroup.Name, dataName = dGroup.Name })
.Join(repository.DeviceTypes, d => d.device.TypeId, t => t.Id, (d, t) => new { d.device, d.dataName, d.managerName, TypeName = t.Name })
.SingleOrDefault();

'AnonymousType#1' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'AnonymousType#1' could be found (are you missing a using directive or an assembly reference?)

有人可以帮忙吗?

最佳答案

(device, mGroup) => new { device, mGroup.Name } 行中的

mGroup 实际上代表了整个集合。您需要对其执行 Select 操作:

(device, mGroup) => new { Device = device, NameGroup = mGroup.Select(m => m.Name) }

查看 MSDN GroupJoin 上的页面以获取更多信息。

关于c# - LINQ GroupBy 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15205425/

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