hadi.k hadi.k - 1 year ago 45
C# Question

how to get all of string values from dictionary and object in C#

how can i get all string values from this dictionary

class MyObject
public string MyString { get; set; }
public int MyInteger { get; set; }
Dictionary<int, MyObject> dictionary = new Dictionary<int, MyObject>();

how can i get all Mystring into a string[] ?

Answer Source

You can use this:

string[] result = dictionary.Values.Select(x=> x.MyString).ToArray();

A Dictionary object has 2 Properties : Keys and Values . You can make use of them when you want.

  • Values contains a Collection of all the Values inside the dictionary.
  • Select is used as a projection to get only the MyString property in MyObject.
  • ToArray extension method converts the result into an array as the expected result in your question.