ccsv
ccsv

Reputation: 8669

Counting non zero values in a dictionary of arrays with LINQ

I have a dictionary of arrays

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

}

If I want to do an operation on the count of the columns such as v*column count I would do this:

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

What is the LINQ code to perform operations such as count on rows with non zeros?

If I use a loop to count them it would be

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

        }

So if I were to do v/column count then all items in a would be divided by 3, all items in b would be divided by 3 and all items in c would be divided by 4

Upvotes: 0

Views: 2031

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109792

Is this what you want?

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

This will set the values to NaN for a row if all the elements of that row are zero. If instead you want to make the results for that row zero, you could change the code to:

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()
);

Upvotes: 2

Sujith C Nair
Sujith C Nair

Reputation: 116

If you just need a sum of all non zero values in all the dictionary items you can use

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

If you need to iterate through all the key value pairs and you wish not to use a foreach loop then you have to come up with an extension method of your own as shown below

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

And you can use it like this

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

Upvotes: 0

Related Questions