I have an object that I need to get some fields from just the first one matched. The key thing is "prices" will either be sorted in ascending or descending "base" order. Find the first matching "base" and also make sure "availability.amount" qualifies, then finally return the "base", "priceTypeID" and "priceLevelID". Here is short snippet of the code that doesn't give me what I need; basically, one result gives me 3 matches while another doesn't give me the "priceLevelID".
The criteria I have below should return "base"=4000, "priceTypeID"="45082" and "priceLevelID"="2650"
public class PriceInfo
{
public class Availability
{
public int amount { get; set; }
}
public class Price
{
public int @base { get; set; }
public string priceTypeID { get; set; }
}
public class PriceLevel
{
public string priceLevelID { get; set; }
public Availability availability { get; set; }
public List<Price> prices { get; set; }
}
public class ZonePrice
{
public List<PriceLevel> priceLevels { get; set; }
}
public class OfferPrice
{
public List<ZonePrice> zonePrices { get; set; }
}
public class RootObject
{
public List<OfferPrice> offerPrices { get; set; }
}
}
class Program
{
static void Main(string[] args)
{
var json = @"{
""offerPrices"": [
{
""zonePrices"": [
{
""priceLevels"": [
{
""priceLevelID"": ""1653"",
""availability"": {
""amount"": 296
},
""prices"": [
{
""base"": 2000,
""priceTypeID"": ""45082""
}
]
},
{
""priceLevelID"": ""1029"",
""availability"": {
""amount"": 300
},
""prices"": [
{
""base"": 3000,
""priceTypeID"": ""45082""
}
]
},
{
""priceLevelID"": ""2650"",
""availability"": {
""amount"": 400
},
""prices"": [
{
""base"": 4000,
""priceTypeID"": ""45082""
}
]
}
]
}
]
}
]
}";
var obj = JsonConvert.DeserializeObject<PriceInfo.RootObject>(json);
var queryResult1 = obj.offerPrices[0].zonePrices[0].priceLevels.Where(w => w.availability.amount >= 2 &&
w.prices.OrderByDescending(o => o.@base).Any(w2 => w2.@base > 1000 && w2.@base < 300000)).FirstOrDefault();
var queryResult2 = obj.offerPrices[0].zonePrices[0].priceLevels.Select(o => new { o.prices, o.priceLevelID, o.availability.amount }).
Select(o2 => o2.prices.OrderByDescending(o3 => o3).Where(w => w.@base > 1000 && w.@base < 300000).
Select(s => new { o2.priceLevelID, s.priceTypeID, s.@base, o2.amount }).First()).
Where(w2 => w2.amount > 2).First();
