I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?
public static List<T> Sample<T>(this List<T> list, int n)
{
var samples = new List<T>();
var divisor = list.Count/n;
for (var i = 0; i < list.Count; i++)
if (samples.Count == i/divisor)
samples.Add(list[i]);
return samples;
}
Hm, what about:
return Enumerable.Range(0,n).Select(i=>list[(i*list.Count)/(n-1)]);
Not that it really matters, but this gives you a slightly better complexity (O(n)
instead of O(list.Count)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With