Nigel Lovelace
Nigel Lovelace

Reputation: 11

How to convert a list of key-value pair types (from object to string)

How do I convert a list of key-value pairs (String, Object) to a list of key value pairs (string, string)?

Upvotes: 1

Views: 3111

Answers (4)

Zebi
Zebi

Reputation: 8882

If the value is of type string you can just cast it:

var result = source.Select(x => new KeyValuePair<string,string>(x.key,(string)x.value)

If the value needs to be converted you can either use .ToString() as already suggested or use a converter function. Maybe your second object is a Person class with a First and LastName Property and you want to get a full name as result:

var result = source.Select(x => new KeyValuePair<string,string>(x.key, string.Format("{0} {1}", ((Person)x.Value).FirstName, ((Person)x.Value).SecondName))

Of course you can use a method to simplify your conversion

var result = source.Select(Convert);

private KeyValuePair<string,string> Convert(KeyValuePair<string,object> pair)
{
    var key = pair.Key;
    var person = (Person)pair.Value;
    var fullName = string.Format("{0} {1}", person.FirstName, person.LastName);

    return new KeyValuePair<string,string>(key, fullName);
}

Upvotes: 1

Alexander Efimov
Alexander Efimov

Reputation: 2687

List<KeyValuePair<string, object>> list = ...
List<KeyValuePair<string, object>> castedItemsList = 
 list
    .Select(item => new KeyValuePair<string, string>(item.Key, item.Value.ToString()))
    .ToList();

Upvotes: 1

Tejs
Tejs

Reputation: 41236

Using LINQ, you can do something like this:

var newList = oldList.Select(kv => new KeyValuePair<string, string>(kv.Key, kv.Value.ToString())).ToList()

Of course, the ToString representation may not be exactly what you are expecting if it's some complex type, but you get the idea.

Upvotes: 1

Alexis
Alexis

Reputation: 406

You would have to Cast those objects.

Upvotes: 0

Related Questions