Convert dictionary to list collection in C#

C#ListDictionary

C# Problem Overview


I have a problem when trying to convert a dictionary to list.

Example if I have a dictionary with template string as key and string as value. Then I wish to convert the dictionary key to list collection as a string.

Dictionary<string, string> dicNumber = new Dictionary<string, string>();
List<string> listNumber = new List<string>();

dicNumber.Add("1", "First");
dicNumber.Add("2", "Second");
dicNumber.Add("3", "Third");

// So the code may something look like this
//listNumber = dicNumber.Select(??????);

C# Solutions


Solution 1 - C#

To convert the Keys to a List of their own:

listNumber = dicNumber.Select(kvp => kvp.Key).ToList();

Or you can shorten it up and not even bother using select:

listNumber = dicNumber.Keys.ToList();

Solution 2 - C#

Alternatively:

var keys = new List<string>(dicNumber.Keys);

Solution 3 - C#

If you want to use Linq then you can use the following snippet:

var listNumber = dicNumber.Keys.ToList();

Solution 4 - C#

If you want convert Keys:

List<string> listNumber = dicNumber.Keys.ToList();

else if you want convert Values:

List<string> listNumber = dicNumber.Values.ToList();

Solution 5 - C#

foreach (var item in dicNumber)
{
    listnumber.Add(item.Key);
}

Solution 6 - C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

Solution 7 - C#

List<string> keys = dicNumber.Keys.ToList();
List<string> values = keys.Select(i => dicNumber[i]).ToList();

This ensures that dicNumber[keys[index]] == values[index] for each possible index.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdy CuView Question on Stackoverflow
Solution 1 - C#Justin NiessnerView Answer on Stackoverflow
Solution 2 - C#stuartdView Answer on Stackoverflow
Solution 3 - C#Pop CatalinView Answer on Stackoverflow
Solution 4 - C#daniele3004View Answer on Stackoverflow
Solution 5 - C#explorerView Answer on Stackoverflow
Solution 6 - C#arunView Answer on Stackoverflow
Solution 7 - C#2474101468View Answer on Stackoverflow