[英]Get value from property if not empty, otherwise get other property with Linq
I have a Linq query with which i get data from an object like so: 我有一个Linq查询,通过它我可以从这样的对象中获取数据:
var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => a.Name).ToArray()
);
This works fine so far, but sometimes the Attachments.Name
property is empty. 到目前为止,此方法工作正常,但有时
Attachments.Name
属性为空。 Then i'd like to get the value of another property. 然后,我想获取另一个属性的值。
To illustrate: 为了显示:
var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => a.Name).ToArray()
// If Attachments.Name == Empty, then get
w => w.EquipmentCode
);
How can i do this in a Linq query? 如何在Linq查询中做到这一点?
var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => a.Name)
.DefaultIfEmpty(w.EquipmentCode)
.ToArray()
);
This retrieves all attachment names, if no attachments are there, an array with a single item containing the EquipmentCode
value is returned. 这将检索所有附件名称,如果不存在附件,则返回包含单个项目的数组,其中包含
EquipmentCode
值。
If the EquipmentCode
property is defined on the Attachment
and you need it as fallback value for each attachment, then check Jon Skeet's answer. 如果在
Attachment
上定义了EquipmentCode
属性,并且您需要将其作为每个附件的后备值,请检查Jon Skeet的答案。
Sounds like you just want the conditional operator: 听起来您只需要条件运算符:
var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => string.IsNullOrEmpty(a.Name)
? a.EquipmentCode : a.Name)
.ToArray());
You could make your Select statement use a lambda and manually check the property like so: 您可以使Select语句使用lambda并手动检查属性,如下所示:
var attachedItems = items.ToDictionary(
w => w.Number,
w => w.Attachments.Select(a => {
if(String.IsNullOrEmpty(a.Name) == false)
return a.Name;
return a.EquipmentCode;
}).ToArray()
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.