Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda with generic

Tags:

c#

generics

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.

like image 213
Irene Lee Avatar asked Jun 09 '26 11:06

Irene Lee


1 Answers

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]));
like image 92
Robert McKee Avatar answered Jun 12 '26 12:06

Robert McKee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!