I'm merely trying to pass in a lambda function which results in a string to generally populate a special kind of lookup list. I'm trying to rewrite some code using higher order functions. The problem is that the Add method does not like the keySelector function. Here is the code, how I get it to compile please:
public static KeyedLookupList<TSource> Slug<TSource>(this List<TSource> items, Func<TSource, string> keySelector) { var keyedLookupList = new KeyedLookupList<TSource>(); foreach (var item in items) { keyedLookupList.Add(keySelector, item); } return keyedLookupList; } Here is the Add method:
public override void Add(string key, TValue value) { base.Add(new KeyValuePair<string, TValue>(key, value)); } The compiler gives the following error:
Error CS1503 Argument 1: cannot convert from 'System.Func<TSource, string>' to 'string' Resolved thanks to @peeyush singh:
public static KeyedLookupList<TSource> Slug<TSource>(this List<TSource> items, Func<TSource, string> keySelector) { var keyedLookupList = new KeyedLookupList<TSource>(); foreach (var item in items) { keyedLookupList.Add(keySelector(item), item); } return keyedLookupList; }
Add()hasstringas first parameter, you are trying to give itFunc<TSource, string>. What are you trying to achieve?TValue valueinpublic override void Add(string key, TValue value)method?KeyValuePairr<string, TValue>also hasstringas first parameter (the key)... What are you actually trying to do? I don't think you wantFuncas key.