Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# KeyValuePair<string, int> List - to <string> without preserving the int value

Tags:

c#

list

key-value

My initialization is:

List<string> convertedList = new List<string>();  
List<KeyValuePair<string, int>> originalList = new List<KeyValuePair<string, int>>();

And I basically want to populate convertedList with only the string values in originalList
So if originalList has some items: ["foo",5],["bar",16],["baz",100],
I want convertedList to contain: ["foo"],["bar"],["baz"]
So far I've tried:

for (int i = 0; i <= originalList.Count; i++)
{
    convertedList.Add(actions.ToString());
}

but with no luck.
Oh, and keep in mind that I'm a newbie and the answers to this might be really obvious.
Thanks for helping me out!
And how would I go about proceeding if I want to convert only the first X items?

like image 408
Стефан Дончев Avatar asked Sep 18 '25 09:09

Стефан Дончев


2 Answers

 List<String> convertedList = originalList.Select(x => x.Key).ToList();

Or:

  convertedList.AddRange(originalList.Select(x => x.Key));
like image 133
Harry Avatar answered Sep 20 '25 01:09

Harry


Sticking to the original syntax:

foreach (KeyValuePair<string, int> kvp in originalList)
{
    convertedList.Add(kvp.Key);
}
like image 41
John Avatar answered Sep 20 '25 00:09

John