用linq替换foreach循环 [英] Replace foreach loop with linq

查看:58
本文介绍了用linq替换foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图替换代码

foreach (var discovery in mpwrapper.parser.Discoveries)
{
   solution.AddFile("Discoveries", discovery.DisplayStringName + ".mpx", discovery);
}

具有以下linq表达式

with the following linq expression

mpwrapper.parser.Discoveries.Select(
                    s => solution.AddFile("Discoveries", s.DisplayStringName + ".mpx", s));

但是出现错误

方法的类型参数 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, 无法从用法中推断出System.Func)'.尝试 明确指定类型参数.

The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

如何将此foreach循环转换为linq查询,在其中我对IEnumerable集合中的每个对象执行一个方法?

How to convert this foreach loop to linq query where I execute a method on each object in my IEnumerable collection?

推荐答案

我认为您需要的是ForEach方法;)

I think what you need is the ForEach method ;)

mpwrapper.parser.Discoveries.ToList().ForEach(s => { solution.AddFile("Discoveries", s.DisplayStringName + ".mpx", s); });

这篇关于用linq替换foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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