C# – Replace foreach loop with linq

clinq

I tried to replace code

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

with the following linq expression

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

But got an error

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.

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

Best Answer

I think what you need is the ForEach method ;)

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