我有这个查询
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
var query =
from n in names
where n.Contains ("a") // Filter elements
orderby n.Length // Sort elements
select n.ToUpper(); // Translate each element (project)
foreach(var item in query)
Console.WriteLine(item);
完美运行,按预期提供结果JAY MARY HARRY
。
但是当我运行这个
时string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
var query2 = names.Where(n=> n.Contains("a")).OrderBy(n=>n.Length).Select(n=>n.ToUpper);
foreach(var item in query2)
Console.WriteLine(item);
我收到此消息The type arguments for method 'System.Linq.Enumerable.Select<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
我也尝试过这个
var query2 = names.Where(n=> n.Contains("a")).OrderBy(n=>n.Length).Select<string, string>(n=>n.ToUpper);
它说Cannot convert method group 'ToUpper' to non-delegate type 'string'. Did you intend to invoke the method? Cannot convert lambda expression to delegate type 'System.Func<string,string>' because some of the return types in the block are not implicitly convertible to the delegate return type.
我不知道发生了什么事?可以任何人告诉我为什么查询语法工作正常方法语法不起作用吗?
答案 0 :(得分:4)
您在ToUpper
之后缺少一对括号:
var query2 = names
.Where(n=> n.Contains("a"))
.OrderBy(n=>n.Length)
.Select(n=>n.ToUpper() /* <<== HERE */);
答案 1 :(得分:3)
您需要将ToUpper作为方法调用(带括号):
var query2 = names.Where(n=> n.Contains("a")).OrderBy(n=>n.Length).Select(n=>n.ToUpper());