Natanael Nunes
Natanael Nunes

Reputation: 13

What is the best way to convert dictionary to a custom KeyValuePair type list?

I have a class:

public class MyKeyValuePair
{
    public string Key;
    public string Value;

    ...
}

I would like to know if there's a better way of doing it than this:

List<MyKeyValuePair> myList;
Dictionary<string,string> dict;

foreach(var pair in dict)
{
    myList.add(new MyKeyValuePair(pair.Key, pair.Value))
}

Upvotes: 0

Views: 419

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

As @Corak pointed out in the comments, you could just use KeyValuePair<TKey,TValue> Struct instead of making your own MyKeyValuePair class:

var list = dict
    .Select(x => new KeyValuePair<string, string>(x.Key, x.Value))
    .ToList();

Or better yet:

var list = new List<KeyValuePair<string, string>>(dict)

Even better:

var list = dict.ToList();

The second and third approaches work because Dictionary<TKey,TValue> implements IEnumerable<KeyValuePair<TKey,TValue>>(), which is a constructor of List<KeyValuePair<TKey,TValue>>(). This also means it can use the ToList extension method.

The structs are also copied by value, not by reference. This is also stated in MSDN:

Structure types have value semantics. That is, a variable of a structure type contains an instance of the type. By default, variable values are copied on assignment, passing an argument to a method, and returning a method result. In the case of a structure-type variable, an instance of the type is copied. For more information, see Value Types.

Upvotes: 1

fubo
fubo

Reputation: 45947

Linq approach

Dictionary<string,string> dict; //input
List<MyKeyValuePair> result = dict.Select(x => new MyKeyValuePair() { 
                                                 Key = x.Key, 
                                                 Value = x.Value}).ToList();

Upvotes: 4

Related Questions