Home > Net >  Add value from Dictionary to Array in c#
Add value from Dictionary to Array in c#

Time:12-08

I have a Dictionary I want to add value in List or Array value. I created the below function:

public static void Main ()
{
    // string [] selected;
    List<string> selected = new List<string>();
    var data = new Dictionary<string, string>()
    {
        {"A", "a"},
        {"B", "b"},
        {"C", "c"},
    };
    foreach (var result in data)
    {
        selected.Append(result.Value);
        // Console.WriteLine(result.Value);
        // selected.Add(result.Value);
        Console.WriteLine(selected);
    }
}

But this gets below output:

System.Collections.Generic.List1[System.String] System.Collections.Generic.List1[System.String] System.Collections.Generic.List`1[System.String]

Please advice

CodePudding user response:

To add the values from a Dictionary to a List or array, you can use the Add method of the List class or the Add method of the Array class. In your code, you are trying to use the Append method to add the values to the list, but this method does not exist.

Here is an example of how you can use the Add method to add the values from a Dictionary to a List:

// Create a List to store the values
List<string> selected = new List<string>();

// Create a Dictionary
var data = new Dictionary<string, string>()
{
    {"A", "a"},
    {"B", "b"},
    {"C", "c"},
};

// Loop through the Dictionary and add the values to the List
foreach (var result in data)
{
    selected.Add(result.Value);
}

// Print the List
foreach (var value in selected)
{
    Console.WriteLine(value);
}

This code creates a List of strings and a Dictionary with three key-value pairs. It then loops through the dictionary and adds the values to the list using the Add method. Finally, it loops through the list and prints the values.

You can also use the Add method of the Array class to add the values from the dictionary to an array.

CodePudding user response:

Instead of

Console.WriteLine(selected);

do

Console.WriteLine(string.Join(",",selected));

CodePudding user response:

You can achieve this using Linq:

List<string> values = data.Select(item => item.Value).ToList();
  • Related