簡體   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