Irene Lee
Irene Lee

Reputation: 101

Lambda with generic

IDictionary<string, string> map = str.Split('|')
                                     .ToDictionary(s => s.Split('@')[0], s => s.Split('@')[1]);

The above statement works. But I would like to change it to generic for IDictionary

public class CSVMap <TKey, TValue>
{
    public IDictionary<TKey, TValue>  func (string str)
    {
        IDictionary<TKey, TValue> map =  str.Split('|').ToDictionary (ConvertValue<TKey>(s => s.Split('@')[0]), ConvertValue<TValue>(s => s.Split('@')[1]));

    }
    public static T ConvertValue<T>(string value)
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }

and ConvertValue to cast the split strings to the type of TKey and TValue.

But I got these errors for the ConvertValue portions:

error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type

I am not sure what the errors mean or how to fix such a problem.

Upvotes: 3

Views: 164

Answers (1)

Robert McKee
Robert McKee

Reputation: 21477

You are passing a lambda expression to the ConvertValue function rather than the value. Not sure if this does what you expect, but this is the correct syntax atleast.

IDictionary<TKey, TValue> map =  str.Split('|').ToDictionary (s=>ConvertValue<TKey>(s.Split('@')[0]), s=>ConvertValue<TValue>(s.Split('@')[1]));

Upvotes: 5

Related Questions