I checking to see if we have any way to return all the keys to array without using the for each loop (there is no constraint for me to use for each loop i am just looking is there any other way)
Thanks in advance
00:19 A key must be immutable—that is, unable to be changed. These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.
Given a List, the task is to create a dictionary with only keys by using given list as keys.
I'm not certain from your wording whether you want the keys or the values. Either way, it's pretty straightforward. Use either the Keys
or Values
property of the dictionary and the ToArray
extension method.
var arrayOfAllKeys = yourDictionary.Keys.ToArray();
var arrayOfAllValues = yourDictionary.Values.ToArray();
You want the keys or the values?
The keys you can get like this:
dictionary.Keys.ToArray();
The values you can get like this;
dictionary.Values.ToArray();
This ToArray method is from System.Linq.Enumerable.
string[] myKeys;
myKeys = myDictionary.Keys.ToArray();
Untested, but I don't see why it would work.
You can use:-
dict.Select(p => $"Keys in dict: {p.Key}")
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