Vasile Doe
Vasile Doe

Reputation: 1754

C# lambda expression Try specifying the type arguments explicitly

I am new in C# and I don't understand how to specify args in lambda expressions. I have following code:

Dictionary<string,string> MyDictionary = some key + some value;

var myReultList= MyDictionary.Select(MyMethod).ToList();
var myReult= await Task.WhenAll(myReultList);

private async Task<string> MyMethod(string arg1, string arg2){
    //do some async work and return value
}

how to specify dictionary key as arg1 and dictionary value as arg2 ?

in this code I get error at 2nd row:

Error CS0411 The type arguments for method Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>) cannot be inferred from the usage. Try specifying the type arguments explicitly.

Upvotes: 0

Views: 1722

Answers (1)

Lee
Lee

Reputation: 144126

The elements of a Dictionary<string, string> are KeyValuePair<string, string> so you need to change the parameter type of MyMethod to match:

private async Task<string> MyMethod(KeyValuePair<string, string> pair) 
{
        string arg1 = pair.Key;
        string arg2 = pair.Value;
        ...
}

alternatively you could unpack the values in a lambda:

var myResultList = MyDictionary.Select(kvp => MyMethod(kvp.Key, kvp.Value)).ToList();

Upvotes: 6

Related Questions