Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sampling a list with linq

Tags:

c#

algorithm

linq

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;
}
like image 610
grenade Avatar asked Dec 21 '22 20:12

grenade


1 Answers

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)

like image 107
MartinStettner Avatar answered Jan 09 '23 16:01

MartinStettner