Reputation: 7301
I have these two classes :
public class Result
{
public string plate { get; set; }
public double confidence { get; set; }
public int matches_template { get; set; }
public int plate_index { get; set; }
public string region { get; set; }
public int region_confidence { get; set; }
public long processing_time_ms { get; set; }
public int requested_topn { get; set; }
public List<Coordinate> coordinates { get; set; }
public List<Candidate> candidates { get; set; }
}
public class Candidate
{
public string plate { get; set; }
public double confidence { get; set; }
public int matches_template { get; set; }
}
I have this query :
List<List<Candidate>> lstCandidates =
deserializedProduct.results.Select(i=>i.candidates).ToList();
As you can see I have a list of list<Candidate>
. Every candidate has plate
and confidence
. I need the plate number with maximum confidence in my lstCandidates
. How can get this value?
Upvotes: 1
Views: 133
Reputation: 37299
Use SelectMany
to flatten the inner lists, then order the items by the confidence
value and retrieve the first value.
var result = deserializedProduct.results.SelectMany(item => item.candidates) //Flatten
.OrderByDescending(item => item.confidence) //Order
.FirstOrDefault()?.plate; // Safely take property of first
The ?.
is C# 6.0 Null propagation feature
Upvotes: 2
Reputation: 7672
Actually it's very simple
deserializedProduct.results
.SelectMany(k => k.candidates)
.OrderByDescending(k => k.confidence)
.Select(k=>k.plate)
.FirstOrDefault();
Upvotes: 1
Reputation: 23200
You can use SelectMany
then OrderBy
and use First
methods.
var candidate = deserializedProduct
.results
.SelectMany(i=>i.candidates) // Flatten the collection
.OrderByDescending(p => p.confidence) // Order by descending on confidence property
.First(); // Take the max
Upvotes: 2