Harshil Doshi
Harshil Doshi

Reputation: 3592

Get all the keys in Array of Dictionary

I have an array of dictionaries as Follows:

Dictionary<int, int>[] matrix = new Dictionary<int, string>[10];

I need all the keys saved in this dictionary which I am using in a foreach loop as below:

 foreach (int key in matrix.Keys)
  {

  }

Obviously, matrix.Keys won't work here. So,is there any way to get all the keys of dictionary without looping through the whole array (maybe Linq or something)?

Upvotes: 0

Views: 712

Answers (4)

mjwills
mjwills

Reputation: 23819

To get the sum of all values from all of the dictionaries in the array, I would suggest:

var total = matrix.SelectMany(z => z).Sum(z => z.Value);

or:

var total = matrix.SelectMany(z => z.Values).Sum(z => z);

There is no need to get the Keys since what you are really interested in are the Values.

Upvotes: 1

fubo
fubo

Reputation: 45947

Assuming your result should be a list of keys you could use SelectMany()

IEnumerable<int> result = matrix.SelectMany(x => x.Keys);

https://dotnetfiddle.net/LgIwr7

Upvotes: 4

adjan
adjan

Reputation: 13652

Use LINQ's SelectMany:

var keys = matrix.SelectMany(x => x.Keys);

Upvotes: 5

bommelding
bommelding

Reputation: 3037

 var allKeys = matrix.SelectMany(d => d.Keys);

 foreach (int key in allKeys) ...

Upvotes: 4

Related Questions