【问题标题】:Filter C# collection of float given a minimum difference value between adjacent elements给定相邻元素之间的最小差值,过滤 C# 浮点数集合
【发布时间】:2012-10-14 18:55:30
【问题描述】:

假设我有一个浮动的有序列表(升序)。

我想从中删除下一个元素与自身之间的差异小于给定阈值的每个元素。

我需要这样的东西:

List<float> orderedList;

IEnumerable<float> query = orderedList.Where(currentNum , nextNum => nextNum - currentNum < threshold);

这可能吗?如果是怎么办?

【问题讨论】:

  • 假设阈值为 2,{1,2,3,4,10,20} 的预期输出是多少?根据您的规则,输出将是 {4,10,20}。

标签: c# collections filtering predicate


【解决方案1】:

试试这个:

var filteredElements = new List<float>();
float ? prev = null;
orderedList.ToList().ForEach((e)=>{ 
              if (prev.HasValue)
              {
                  if (e-prev >= threshold)
                       filteredElements.Add(prev.Value);
              } 
              prev = e
         });

【讨论】:

    【解决方案2】:

    试试这个 -

    List<float> orderedList = new List<float>() { 12, 14, 34, 45 };
    List<float> itemsToRemove = orderedList.Where((item, index) =>
                                index < orderedList.Count - 1 &&
                                orderedList[index + 1] - item < threshhold).ToList();
    

    【讨论】:

      【解决方案3】:

      试试这个:

      var ls1 = ls.Where((item, index) => 
                         item - ls[ls.Count == index + 1 ? index : index + 1] >= 0);
      

      希望这会有所帮助!

      【讨论】:

      • 最后一个元素会发生什么?
      • @AustinSalonen,提出了很好的观点,按照建议更新了答案
      【解决方案4】:

      这似乎有效。 (尽管您的问题有一些可能被误解的含义。)

      var input = new List<float>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 18, 21, 24, 27, 29, 35, 40, 46, 59 };
      var output = input.Zip(input.Skip(1).Concat(new[]{float.MaxValue}), (a, b) => new { a, b }).Where(x => x.b - x.a > 2).Select(x => x.a);
      

      这会产生以下输出:

      15, 18, 21, 24, 29, 35, 40, 46, 59
      

      这具有与任何IEnumerable 一起工作的优势。

      【讨论】:

      • +1:谢谢你的好例子。我意识到我的问题有点含糊,但我简化了我实际尝试做的操作。我真正需要的是应用谓词的当前元素的索引。无论如何,您的示例非常有用且有趣,非常感谢。
      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多