LINQ ToDictionary how to get the index of an element?

I have a dictionary that I want to convert to another dictionary using the rule below:

Inputs

Dictionary<string, string> inputs = new Dictionary<string, string>(3) { { "A", "First" }, { "Z", "Third" }, { "J", "Second" } }; 

Output:

 Dictionary<int, string> output = new Dictionary<string, string>(3) { { 0, "First" }, { 1, "Second" }, { 2, "Third" } }; 

Can I do this using lambda syntax and without intermediate objects?

Thanks.

+4
source share
2 answers

The enumeration order of the dictionary is undefined (i.e. the elements have no index), so I'm not sure if this is possible. How will integer values ​​be obtained?

EDIT:

I get it now:

 inputs .OrderBy(input => input.Key) .Select((input, index) = >new {index, input.Value}) .ToDictionary(x => x.index, x => x.Value) 
+6
source

If you can determine what the order should be, then I would do it like this (I selected the order by key):

 Dictionary<string, string> inputs = new Dictionary<string, string>(3) { { "A", "First" }, { "Z", "Third" }, { "J", "Second" } }; var outputs = inputs.OrderBy(i=>i.Key).Select(i=>i.Value).ToArray(); // output // String [] (3 items): First Second Third 

This gives you an array with the indexes you requested (for example, output[0] ).

If you really want the dictionary entries coming back, you can get ienumerable from them like this (you cannot just return the dictionary because they are unordered):

 var outputs = inputs.OrderBy(i=>i.Key).Select( (entry, index) => new KeyValuePair<int, string>(index, entry.Value)); 

Throw .ToArray() there if you need to.

If you really want the dictionary returned, try the following:

 var outputs = inputs.OrderBy(i=>i.Key) .Select((entry, i) => new { entry.Value, i }) .ToDictionary(pair=>pair.i, pair=>pair.Value).Dump(); 

Just keep in mind that the dictionaries are not initially ordered, so if you list it, you must add a .OrderBy again.

+1
source

Source: https://habr.com/ru/post/1345723/


All Articles