使用linq采样列表 [英] Sampling a list with linq
问题描述
我需要一个用于将轴标签添加到图表的辅助方法.我不想在图表中沿轴的每个点都添加标签,因为那样会太忙.因此,我需要定期提取样本.到目前为止,我已经提出了一种满足要求的以下方法,但是我认为必须要有一种更灵巧的方法来使用Linq来完成此任务.谁能想到这可以变得更简洁(n代表我想要返回的样本总数)?
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;
}
推荐答案
嗯,那怎么办:
return Enumerable.Range(0,n).Select(i=>list[(i*list.Count)/(n-1)]);
并不是很重要,但这会给您带来更好的复杂性(O(n)
而不是O(list.Count)
Not that it really matters, but this gives you a slightly better complexity (O(n)
instead of O(list.Count)
这篇关于使用linq采样列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!