Home > Software engineering >  Cannot retrieve object from inner dictionaries/lists
Cannot retrieve object from inner dictionaries/lists

Time:03-14

I am currently trying to get an object deeply nested within a dictionaries and lists.

The object is the ProductPrice object within the ProductInfo dictionaries.

The structure is:

Debug info

I have tried the following LINQ however this only returns me the list (right before the object)

                       var Lis = productInfo
                            .Where(x => x.Key == "Prices")
                            .ToDictionary(x => x.Key, x => x.Value)
                            .Where(x => x.Key == "Prices")
                            .Select(x => x.Value)
                            .ToList()
                            .First();

The productinfo class is a dictionary which is of the type <string, object>. I dont know why the first() command still gives me the full list and not the object itself... any ideas of how to iterate the first dictionary find the prices dictionary then iterate that one. Retrieve the list and finally get the first element of it?

The result of my linq is her:

Linq variable first()

Update Product Info Class:

using System.Collections.Generic;

namespace Dynamicweb.Ecommerce.Integration
{
    public class ProductInfo : Dictionary<string, object>
    {
        public ProductInfo();
    }
}

CodePudding user response:

Hard to be sure and I cannot test this becuase I dont have you classes or data so I can only go off your debug screen shots

 var prices = productInfo["Prices"];

prices seems to be a List of something.something.ProductPrice. But it looks like you want the first one. So its just

 var prices = productInfo["Prices"].First();

I dont see why you need that hugely complex LINQ chain. Or are you truying to extarct someting from the ProductPrice class

CodePudding user response:

You don't need to iterate anything. Your productInfo is a dictionary of objects. You need to cast the value of the dictionary access to the appropriate type (List<ProductPrice>) and operate on that. In this case, you can call First() to get the first item in the list.

var query = ((List<ProductPrice>)productInfo["Prices"]).First();

If it's possible to not have "Prices` in the dictionary or it's not in an expected type or potentially empty, you can check for that.

var query = productInfo.TryGetValue("Prices", out var v) && v is IEnumerable<ProductPrice> e
    ? e.FirstOrDefault()
    : default;
  • Related