简体   繁体   中英

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.

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.

'System.Dynamic.DynamicObject' does not contain a definition for 'itemId'

I have tried x?.itemId , x.?itemId , x.itemId? , and ?x.itemId which seem to be the only places I can capture for nulls.

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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