【问题标题】:Sampling a list with linq使用 linq 对列表进行采样
【发布时间】:2011-05-25 06:57:44
【问题描述】:

我需要一个辅助方法来为图表添加轴标签。我不想在图表中具有值的轴的每个点上添加标签,因为那样会太忙。所以我需要定期提取样本。到目前为止,我已经提出了以下满足要求的方法,但我认为必须有一种更简洁的方法来使用 Linq 完成此操作。谁能想到如何使这更简洁(n 代表我想要返回的样本总数)?

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;
}

【问题讨论】:

  • 你确定采样会给一个不错的轴吗?我会寻找 Min 和 Max 并使用 log10 算术建立一个比例。大多数图表工具都会这样做。
  • @Henk Holterman,看过输出后,我倾向于同意你的看法。
  • 采样是解决此问题的错误方法。我会留下这个问题,因为也许有一天有人会需要一个采样器来做其他事情,但最后,我确实使用了上面的建议。你可以在这里看到结果:stackoverflow.com/questions/25458/…

标签: c# linq algorithm


【解决方案1】:

此解决方案避免在迭代中使用除法,它应该执行得更快。

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;
    }
}

【讨论】:

    【解决方案2】:

    试试

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

    【讨论】:

      【解决方案3】:

      嗯,怎么样:

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

      这并不重要,但这会给您带来更好的复杂性(O(n) 而不是 O(list.Count)

      【讨论】:

        【解决方案4】:
            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();
            }
        

        【讨论】:

          【解决方案5】:

          如果我理解正确:

          int divisor = list.Count / n;
          return list.Where((val, index) => index % divisor == 0).ToList();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-19
            • 1970-01-01
            • 2020-03-12
            • 1970-01-01
            • 2017-03-21
            • 2020-03-08
            相关资源
            最近更新 更多