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?
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 .
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.
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With