用LINQ计算数组字典中的非零值
本文关键字:非零值 字典 数组 LINQ 计算 | 更新日期: 2023-09-27 18:05:01
我有一个数组字典
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
这是你想要的吗?
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()
);
如果您只需要所有字典项中所有非零值的总和,您可以使用
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);
}
}