我是C#的新手,我不明白如何在lambda表达式中指定args.我有以下代码:
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
}
Run Code Online (Sandbox Code Playgroud)
如何将字典键arg1和字典值指定为arg2?
在这段代码中,我在第2行得到错误:
错误CS0411
Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)无法根据用法推断方法的类型参数.尝试显式指定类型参数.
a的元素Dictionary<string, string>是KeyValuePair<string, string>你需要更改MyMethod匹配的参数类型:
private async Task<string> MyMethod(KeyValuePair<string, string> pair)
{
string arg1 = pair.Key;
string arg2 = pair.Value;
...
}
Run Code Online (Sandbox Code Playgroud)
或者你可以在lambda中解压缩值:
var myResultList = MyDictionary.Select(kvp => MyMethod(kvp.Key, kvp.Value)).ToList();
Run Code Online (Sandbox Code Playgroud)