Reputation: 10877
I currently have a list of objects with the following structure:
public class DataPointSet {
public string target{ get; set; }
public List<List<decimal>> datapoints{ get; set; }
}
Everything to append to this list is working but I need to sort it based on the average of every elements first index in the datapoints
list. I currently Linq to get the average:
datapoints.Select(innerList => innerList.First()).Average()
Is there a way to sort this list based on the average of the first element in each element of the datapoints
list?
Sorry if this is confusing, any help would be great, thanks!
Upvotes: 1
Views: 346
Reputation: 8524
Create a class for your datapoints and Override the compare:
public class DataPoint: IComparable<DataPoint>
{
public List<decimal> points;
[...]
public int CompareTo(DataPoint that)
{
if (this.points.Average() > that.points.Average()) return -1;
if (this.points.Average() == that.points.Average()) return 0;
return 1;
}
}
You can then just call Sort on your list.
Upvotes: 0
Reputation: 726609
Since datapoints
is a collection of collections, the call to First()
needs to be made inside a lambda that you pass to Average
, as follows:
IEnumerable<DataPointSet> datapoints = ...
var ordered = datapoints
.OrderBy(pointSet => pointSet.datapoints.Average(point => point.First()));
Upvotes: 2