Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 使用linq选择内部方法_.net_Linq_Select_Lambda_Func - Fatal编程技术网

.net 使用linq选择内部方法

.net 使用linq选择内部方法,.net,linq,select,lambda,func,.net,Linq,Select,Lambda,Func,我有一个包含Id、姓名、年龄等属性的列表。 使用Linq,我可以使用.select(x=>x.Name,x.Age)选择一个或多个属性 得到了一个只有这些属性的可枚举的 现在,我需要在方法内部进行选择。我尝试使用func,但无法打开该方法: void myMethod<T,TSelection>(List<T> Persons, Func<T, TSelection> index) { var Index = list.Select(index); ..

我有一个包含Id、姓名、年龄等属性的列表。 使用Linq,我可以使用.select(x=>x.Name,x.Age)选择一个或多个属性 得到了一个只有这些属性的可枚举的

现在,我需要在方法内部进行选择。我尝试使用func,但无法打开该方法:

 void myMethod<T,TSelection>(List<T> Persons, Func<T, TSelection> index) {

 var Index = list.Select(index);
...
    }

只需将lambda作为第二个参数传递:

myMethod(list, t => t.Age)
运行时将强制lambda成为与
Func
参数兼容的委托。如果编译器无法找出您的类型,那么您可能必须在lambda上指定类型。这通常只是在使用泛型类型参数作为返回类型时才会出现的问题——在这种特殊情况下,您应该不会有问题

如果要选择多个属性而不选择原始类型的新实例,则需要选择一个新的匿名对象(例如,
new{}
)。您可以在lambda中选择您关心的属性:

myMethod(list, t => new { t.Age, t.Name });

谢谢,它没有“列表,…”部分工作。但是,如何选择多个属性?您在原始代码中显示的语法对于选择多个属性是不正确的。我相信你要找的是一个匿名对象。我对答案进行了编辑,以显示您将如何进行预测。
myMethod(list, t => new { t.Age, t.Name });