繁体   English   中英

我如何从具有其他嵌套值的对象数组中的Linq返回单个值整数

[英]How can I return a single value integer from Linq from an array of objects that have other nested values

我试图基于子子字段的值对动态对象的集合进行Linq查询,然后将其他字段的单个值返回为整数。

到目前为止,我有:

int itemId = (
                from x in ((IEnumerable<dynamic>)allpets.pets.collected)
                where x.stats.speciesId == 294
                select x.itemId
             ).SingleOrDefault()

问题是,有时找到的结果没有字段x.itemId ,最终导致异常。

'System.Dynamic.DynamicObject'不包含'itemId'的定义

我尝试过x?.itemIdx?.itemId x.?itemIdx.itemId? ,以及?x.itemId ,这似乎是我唯一可以捕获空值的地方。

另一部分是更复杂的嵌套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();

尝试这个。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM