Sampling a list with linq

I need a helper method to add axis labels to the chart. I don’t want to add a label to every point along the axis that matters on the chart because it’s too busy. Therefore, I need to regularly extract samples. So far, I have come up with the following method that meets the requirements, but I think there should be an easier way in Linq to accomplish this. Can anyone think of a way to make this more concise (n represents the total number of samples I want to return)?

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;
}
+3
source share
5 answers

Hm, and what:

return Enumerable.Range(0,n).Select(i=>list[(i*list.Count)/(n-1)]);

, , (O(n) O(list.Count)

+4

:

int divisor = list.Count / n;
return list.Where((val, index) => index % divisor == 0).ToList();
+3
    public static List<T> Sample<T>(this List<T> list, int n)
    {
        Int32 count = list.Count;
        Int32 interval = count / n;

        return list.Where((item, index) => index % interval == 0).ToList();
    }
+2
source

Try

list.Where((o, index) => index % divisor == 0)
0
source

This solution avoids using iteration division, which should be faster.

public static List<T> Sample<T>(this List<T> list, int n)
{
    return list.Sample(list.Count / n).ToList();
}

public static IEnumerable<T> Sample<T>(this IEnumerable<T> enumerable, int interval) {
    var index = 0;
    foreach (var item in enumerable) {
        if (index == 0) {
            yield return item;
        }
        if (++index == interval) index = 0;
    }
}
0
source

Source: https://habr.com/ru/post/1780212/


All Articles