I have this structure:
private readonly Dictionary<string, Dictionary<string, int>> _storage = new Dictionary<string, Dictionary<string, int>>();
key: Firmware(string): key: Device(string) : value CountOfUsers (int)
I need to get the total of users for each device, but I really don't know how to do it with LINQ. Already tried a lot of variants. Please, help!
For now, I just use a whole function for it
private XlsRow2 GetTotalPerDevice(Dictionary<string, Dictionary<string, int>> storage) { XlsRow2 totalPerDeviceRow = new XlsRow2(); totalPerDeviceRow._Name = "Grand Total"; totalPerDeviceRow.UseBorders = true; foreach (var deviceModel in _allDeviceModels) { foreach (var firmware in storage) { foreach (var device in firmware.Value) { var countOfUsers = 0; if (deviceModel == device.Key) { countOfUsers += device.Value; if (!_totalsPerDevice.ContainsKey(deviceModel)) { _totalsPerDevice.Add(deviceModel, countOfUsers); } else { _totalsPerDevice[deviceModel] += countOfUsers; } } } } } foreach (var deviceModel in _allDeviceModels) { if (_totalsPerDevice.ContainsKey(deviceModel)) { totalPerDeviceRow._AddColumn(_totalsPerDevice.First(k => k.Key == deviceModel.ToString()).Value.ToString()); } else { totalPerDeviceRow._AddColumn(""); } } return totalPerDeviceRow; }
Items select new { Sum(p. Total), Sum(p. Done)};
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
In LINQ, you can find the average of the given sequence by using the Average method. This method returns the average of the elements present in the given sequence or collection. It returns nullable, non-nullable decimal, double, floats, int, etc. values.
Where() returns a new IEnumerable . It is a filtered version (a projection) of the original sequence, and original is left unchanged. ToList() returns a new list using the projection.
Something like this for example?
var result = _storage.SelectMany(x => x.Value) .GroupBy(x => x.Key) .Select(x => new { Device = x.Key, Total = x.Sum(y => y.Value) });
Since the keys for the data that you would like to aggregate is in the second-level dictionary, a good first step would be to dump all key-value pairs from inner dictionaries into a flat sequence. After that all you need is to aggregate the counts, like this:
var res = _storage .SelectMany(d => d.Value) .GroupBy(kvp => kvp.Key) .ToDictionary(g => g.Key, g => g.Sum(kvp => kvp.Value));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With