【问题标题】:Find all elements from index modulo X with specific value in linq在linq中查找具有特定值的索引模X的所有元素
【发布时间】:2011-10-29 10:31:50
【问题描述】:

如何修改我的方法以仅检查模 17 时等于 0 的索引? 我想从该索引中获取所有等于零的项目。

我的List<byte[]> listOfArrays 正在存储具有值0,1 的数组

这是我的方法:

public List<int> Funct(List<byte[]> listOfArrays)
        {
            List<int> pixelsList = new List<int>();
            foreach (byte[] t in listOfArrays)
            {
                //count how many items with value 0
                var pixelsInArray = t.Count(n => n == 0);

                var firstElement = Array.FindIndex(t, i => i == 0);
                var lastElement = Array.FindLastIndex(t, i => i == 0);

                pixelsList.Add(pixelsInArray);
            }
            return pixelsList;
        }

在该方法中,我搜索所有索引。

感谢您的帮助。
PS。如果需要更正,请检查我的语法。

【问题讨论】:

    标签: arrays linq list indexing modulo


    【解决方案1】:

    如果我理解正确,这应该可以解决问题:

      public List<int> Funct(List<byte[]> listOfArrays)
      {
         List<int> pixelsList = new List<int>();
         foreach (byte[] t in listOfArrays)
         {
            int counter = 0;
            t.ForEachWithIndex((value, index) =>
                                  {
                                     if (value == 0 && index % 17 == 0)
                                     {
                                      // your values
                                      counter++;                                      
                                     }
                                  }); 
    
           pixelsList.Add(counter);
         }
    
         return pixelsList;
      }
    

    在以下位置找到扩展名: How do you get the index of the current iteration of a foreach loop?

    namespace MyExtensions
    {
       public static class ForEachExtensions
       {
          public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)
          {
             int idx = 0;
             foreach (T item in enumerable)
                handler(item, idx++);
          }
       }
    }
    

    【讨论】:

    • 是的,字节不要立即添加到列表中,而只是计数:) 但这段代码也很有帮助
    • 好的,我修好了 :) 你是这个意思吗?
    • 是的,它应该是,但它对我不起作用。 ForEachWithIndex 无法识别。我正在尝试找出原因..
    • 我把这些类放在同一个命名空间中,你确定你在 ForEachExtensions 中添加了“using”(如果它在另一个命名空间中)?
    • yeap :) 你应该把它放在你的项目中的某个地方,默认情况下它不在 .Net 框架中
    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多