[英]How can I return a single value integer from Linq from an array of objects that have other nested values
I am trying to do a Linq query on a collection of dynamic objects based on the value of a sub-sub field, and then return the single value of a different field as an integer. 我试图基于子子字段的值对动态对象的集合进行Linq查询,然后将其他字段的单个值返回为整数。
What I have so far is : 到目前为止,我有:
int itemId = (
from x in ((IEnumerable<dynamic>)allpets.pets.collected)
where x.stats.speciesId == 294
select x.itemId
).SingleOrDefault()
The problem is, sometimes the result found has no field x.itemId
which ends up causing an exception. 问题是,有时找到的结果没有字段x.itemId
,最终导致异常。
'System.Dynamic.DynamicObject' does not contain a definition for 'itemId' 'System.Dynamic.DynamicObject'不包含'itemId'的定义
I have tried x?.itemId
, x.?itemId
, x.itemId?
我尝试过x?.itemId
, x?.itemId
x.?itemId
, x.itemId?
, and ?x.itemId
which seem to be the only places I can capture for nulls. ,以及?x.itemId
,这似乎是我唯一可以捕获空值的地方。
The other part, is this is part of a more complex nested linq select, and where the value 294
is located, is actually p.stats.speciesId
(snippet below so you can see why this needs to be inline) 另一部分是更复杂的嵌套linq选择的一部分,值294
所在的位置实际上是p.stats.speciesId
(下面的代码段,因此您可以看到为什么需要内联)
List<MasheryTypes.pet> pets = ((IEnumerable<dynamic>)json.pets).Select(
p => new MasheryTypes.pet(
Convert.ToBoolean(p.canBattle),
p.creatureId,
p.name,
p.family,
p.icon,
p.qualityId,
new MasheryTypes.petstats(
p.stats.speciesId,
p.stats.breedId,
p.stats.petQualityId,
p.stats.level,
p.stats.health,
p.stats.power,
p.stats.speed
),
p.strongAgainst?[0],
p.typeId,
p.weakAgainst?[0],
cageable.Any(
c => c == p.creatureId
),
p.itemId = (from x in ((IEnumerable<dynamic>)allpets.pets.collected)
where x.stats.speciesId == p.stats.speciesId
select x.itemId).SingleOrDefault()
)
).ToList();
Try this. 尝试这个。
int itemId = (
from x in ((IEnumerable<dynamic>)allpets.pets.collected)
where x.GetType().GetProperty("itemId") != null && x.stats.speciesId == 294
select x.itemId
).SingleOrDefault()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.