【问题标题】:Counting non zero values in a dictionary of arrays with LINQ使用 LINQ 计算数组字典中的非零值
【发布时间】:2015-07-28 09:37:30
【问题描述】:

我有一个数组字典

public static void Main(string[] args)
{
    Dictionary<string, int[]> ret = new Dictionary<string, int[]>();
    int[] a = {1,0,3,4,0};
    int[] b = { 3, 0, 9, 10, 0};
    int[] c = {2,3,3,5,0};
    ret.Add("Jack", a);
    ret.Add("Jane", b);
    ret.Add("James", c);

}

如果我想对 v*column count 等列的计数进行操作,我会这样做:

        Dictionary<string, double[]> colcnt = ret.ToDictionary(r => r.Key,
                         r => r.Value.Select(v => v == 0 ? 0 :
                                  (double)v / (ret.Values.Count()) //equation
                                                   ).ToArray());

什么是 LINQ 代码来执行诸如计数非零行之类的操作?

如果我使用循环来计算它们,那就是

        foreach (var item in ret)
        {
          int vals= item.Value.Count(s => s != 0);

        }

所以如果我做v/column count,那么a 中的所有项目都将除以3,b 中的所有项目将除以3,c 中的所有项目将除以4

【问题讨论】:

  • 为什么你的代码不够用?你使用 linq 很好。
  • 您想要所有行的总计数,还是行计数数组?
  • @MatthewWatson 的行数(不包括 0 的值)
  • 您尝试进行的数学方程式究竟是什么?
  • @shay__ 只是简单地将每个单元格除以非零行的总数。

标签: c# linq dictionary


【解决方案1】:

这是你想要的吗?

var result = ret.ToDictionary
(
    r => r.Key, 
    v => v.Value.Select(n => (double)n/v.Value.Count(i => i != 0)).ToArray()
);

如果该行的所有元素都为零,这会将该行的值设置为NaN。相反,如果您想让该行的结果为零,您可以将代码更改为:

var result = ret.ToDictionary
(
    r => r.Key, 
    v => v.Value.Select(n =>
    {
        double count = v.Value.Count(i => i != 0);
        return (count > 0) ? n/count : 0.0;
    }).ToArray()
);

【讨论】:

  • 不是一个总和,而是一个计数,所以行 a = 3, b=3, c=4。如果我要对字典做一个 for 循环,我会做 item.Value.Count(s =&gt; s != 0)
  • 感谢NaN 设置
【解决方案2】:

如果您只需要所有可以使用的字典项中所有非零值的总和

ret.Sum(x => x.Value.Count(y => y != 0));

如果您需要遍历所有键值对并且不希望使用 foreach 循环,那么您必须提出自己的扩展方法,如下所示

 public static class DictionaryExtensionMethods
{
    public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> method)
    {
        foreach (T obj in enumerable)
        {
            method(obj);
        }
    }
}

你可以这样使用它

 class Program
{
    static void Main()
    {
       var ret = new Dictionary<string, int[]>();
        int[] a = { 1, 0, 3, 4, 0 };
        int[] b = { 3, 0, 9, 10, 0 };
        int[] c = { 2, 3, 3, 5, 0 };
        ret.Add("Jack", a);
        ret.Add("Jane", b);
        ret.Add("James", c);
        ret.ForEach(x => Write(x.Value.Count(y => y !=0), x.Key));
        Console.ReadLine();
    }

    public static void Write(int count, string key)
    {
        Console.WriteLine("Count of non zeroes in {0} is {1}", key, count);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2020-02-23
    • 1970-01-01
    相关资源
    最近更新 更多