hadi.k
hadi.k

Reputation: 25

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

How can I get all the 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[] ? thanks

Upvotes: 0

Views: 2883

Answers (2)

Guy haimovitz
Guy haimovitz

Reputation: 1625

 string[] allStrings = dictionary.Values.ToArray();

Upvotes: 0

Zein Makki
Zein Makki

Reputation: 30032

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.

Upvotes: 2

Related Questions