Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Convert' Dictionary<string,int> into List<object>

Tags:

c#

.net

linq

I have a Dictionary<string,int> dictionary1 and I need to convert it into a List<Data> where Data has the properties lable = dictionary1.key and value = dictionary1.value. I don't want to use a for/foreach loop (written by myself) because in order to avoid it I am trying to use a Dictionary.

Another option would be having two different dictionaries (dictionary2 and dictionary3) where dictionary2<string,keyOfDictionary1> and dictionary3<string,valueOfDictionary1>.

Do I make sense? Is that possible? Is there a better option?

like image 848
Jenninha Avatar asked Jul 13 '12 12:07

Jenninha


People also ask

How to Convert Dictionary to list of string in C#?

In C#, a dictionary can be converted into a list using the ToList() method as a part of the System. Linq extensions. A dictionary cannot be converted to a List<string> directly because the return type of dictionary is KeyCollection .

What is TKey and TValue?

In Dictionary<TKey,TValue> TKey is the type of the Key, and TValue is the Type of the Value. It is recommended that you use a similar naming convention if possible in your own generics when there is nore than one type parameter.

Can we convert list to object?

A list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);


1 Answers

Assuming:

class Data
{
    public string Label { get; set; }

    public int Value { get; set; }
}

Then:

Dictionary<string, int> dic;
List<Data> list = dic.Select(p => new Data { Label = p.Key, Value = p.Value }).ToList();
like image 54
abatishchev Avatar answered Oct 22 '22 17:10

abatishchev