1

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; } 
8
  • Add() has string as first parameter, you are trying to give it Func<TSource, string>. What are you trying to achieve? Commented Dec 5, 2018 at 8:02
  • Your add method takes a string as the first parameter, you are sending it a func and thats what the compiler is complaining. Should you call to add not be like Add(keySelector(item), item) Commented Dec 5, 2018 at 8:02
  • What type of TValue value in public override void Add(string key, TValue value) method? Commented Dec 5, 2018 at 8:06
  • 1
    @CarneyCode well KeyValuePairr<string, TValue> also has string as first parameter (the key)... What are you actually trying to do? I don't think you want Func as key. Commented Dec 5, 2018 at 8:12
  • 1
    @CarneyCode Please read my previous comment. Commented Dec 5, 2018 at 8:18

1 Answer 1

2

Instead of passing the func you need to pass the evaluated func, so like

keyedLookupList.Add(keySelector(item), item); 
Sign up to request clarification or add additional context in comments.

1 Comment

Utterly correct! I wasn't performing the evaluation anywhere. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.