gpt4 book ai didi

c# - 如果不为空则从属性中获取值,否则使用 Linq 获取其他属性

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

我有一个 Linq 查询,我用它从一个对象中获取数据,如下所示:

var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => a.Name).ToArray()
);

目前为止一切正常,但有时 Attachments.Name 属性为空。然后我想获得另一个属性的值。

举例说明:

var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => a.Name).ToArray()
// If Attachments.Name == Empty, then get
w => w.EquipmentCode
);

我如何在 Linq 查询中执行此操作?

最佳答案

var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => a.Name)
.DefaultIfEmpty(w.EquipmentCode)
.ToArray()
);

这将检索所有附件名称,如果没有附件,则返回一个包含单个项目的数组,该项目包含 EquipmentCode 值。

如果 EquipmentCode 属性是在 Attachment 上定义的,并且您需要它作为每个附件的后备值,那么请查看 Jon Skeet 的回答。

关于c# - 如果不为空则从属性中获取值,否则使用 Linq 获取其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17723629/

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