dictionary to array c# code example
Example 1: .net core convert keycollection to array
string[] keys = new string[dictionary.Keys.Count];
dictionary.Keys.CopyTo(keys, 0);
Example 2: Disctionary to Array
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
var foos = dict.Values.ToArray();
Example 3: c# array to dictionary
You can use the overload of Select which includes the index:
var dictionary = array.Select((value, index) => new { value, index })
.ToDictionary(pair => pair.value, pair => pair.index);
Or use Enumerable.Range:
var dictionary = Enumerable.Range(0, array.Length).ToDictionary(x => array[x]);
Note that ToDictionary will throw an exception if you try to provide two equal keys. You should think carefully about the possibility of your array having two equal values in it, and what you want to happen in that situation.
I'd be tempted just to do it manually though:
var dictionary = new Dictionary<string, int>();
for (int i = 0; i < array.Length; i++)
{
dictionary[array[i]] = i;
}