使用LINQ进行方法调用 [英] Method invocation using LINQ

查看:66
本文介绍了使用LINQ进行方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

I have follwing scenario:

List<ABC> abc = new List<ABC>()
           {
               new ABC { a = "YYY", b = "rrrr" },
               new ABC { a = "www", b = "ddd" }
           };

          //not working
           string result= abc.ForEach(a => ABC.MyMethod(a.b));
           //working
          var result1= abc.Select(a => ABC.MyMethod(a.b)).ToList();





第一个LINQ表达式给出错误,说不能隐式地将类型'void'转换为'string',而第二个表达式正在工作。

任何人都可以解释为什么?



这是我的方法体:



The first LINQ expression is giving error saying "Cannot implicitly convert type 'void' to 'string'" while the second one is working.
Can anybody explain why?

This is my method body:

public static string MyMethod(string input)
       {
           var c = input;
           return c;
       }

推荐答案

嗯......这很明显! :笑:

第二个第一个:

从ABC对象的集合中,选择返回值 - 这是字符串 - 并将其转换为字符串列表。那里没什么好笑的。



第一个虽然只是看看MSDN文档:列表< T> .ForEach方法 [ ^ ]你将会看到它返回一个空白 - 并且你根本没有任何东西可以投无效!

ForEach不返回集合,也不返回任何内容。
Well... it's pretty obvious! :laugh:
The second one first:
From a collection of ABC objects, select the return value - which is string - and convert it to a list of strings. Nothing funny there.

The first one though just takes a look at the MSDN documentation: List<T>.ForEach Method[^] and you will see it returns a void - and there is nothing you can cast a void to at all!
ForEach doesn't return a collection, it doesn't return anything.


这篇关于使用LINQ进行方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆