Reputation: 81
I have an API that compiles similar information from various sources. What I need to do is compare those sources and save the one with the highest confidence level to a variable. I can think of some long winded ways to maybe accomplish this, create multiple arrays or lists and iterate over each one until I'm left with the highest value, but I'm wondering if there is an easier way to do this using something linq.
{
"modeled_response": [
{
"source": "arturo_bulk_import",
"attributes": {
"roof_shape": {
"value": "Gable",
"confidence": 0.9522576226679909
},
"roof_slope": {
"value": "Low",
"confidence": 0.8674100762576565
}
}
},
{
"source": "region_state_arturo_bulk_import",
"attributes": {
"roof_shape": {
"value": "Gable",
"confidence": 0.8467693167596497
},
"roof_slope": {
"value": "Low",
"confidence": 0.8515481815500642
}
}
},
{
"source": "region_zipcode5_arturo_bulk_import",
"attributes": {
"roof_shape": {
"value": "Gable",
"confidence": 0.8353433674418161
},
"roof_slope": {
"value": "Low",
"confidence": 0.868985703016765
}
}
}
],
}
And then I'm deserializing the object and saving it to a list of results. Not sure where to go from here to retrieve the value with the greatest confidence level
class Program
{
static void Main(string[] args)
{
const string FILE_PATH = @"";
StreamReader r = new StreamReader(FILE_PATH);
string json = r.ReadToEnd();
RootObject deserializedProduct =
JsonConvert.DeserializeObject
<RootObject>(json);
List<RoofShape> resultsList = new List<RoofShape>();
int index = 0;
do
{
resultsList.Add(new RoofShape
{
confidence = deserializedProduct.modeled_response[index]
.attributes.roof_shape.confidence,
value = deserializedProduct.modeled_response[index]
.attributes.roof_shape.value
});
index++;
} while (deserializedProduct.modeled_response.Count > index);
}
}
public class RootObject
{
public string normalized_address { get; set; }
public string created_timestamp { get; set; }
public List<ModeledResponse> modeled_response { get; set; }
}
public class ModeledResponse
{
public string source { get; set; }
public Attributes attributes { get; set; }
}
public class Attributes
{
public string attributes { get; set; }
public RoofShape roof_shape { get; set; }
}
public class RoofShape
{
public string value { get; set; }
public decimal confidence { get; set; }
}
Upvotes: 0
Views: 256
Reputation: 11364
Following code generates the ModeledResponse
variable with the highest confidence level using Linq.
RootObject deserializedProduct = JsonConvert.DeserializeObject<RootObject>(json);
decimal maxConfidenceInAllModels = deserializedProduct.modeled_response.Max(x => x.attributes.roof_shape.confidence);
ModeledResponse confident = deserializedProduct.modeled_response
.Where(x => x.attributes.roof_shape.confidence == maxConfidenceInAllModels)
.FirstOrDefault();
Using the Max
method, you can find out what the highest confidence level is.. and then use that number to filter out the list.
Upvotes: 1