Replace foreach loop with linq

I tried replacing the 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 an error was received

Type arguments for the method 'System.Linq.Enumerable.Select (System.Collections.Generic.IEnumerable, System.Func)' cannot be taken out of use. Try to explicitly specify the type arguments.

How to convert this foreach loop to linq request where I execute a method for every object in my IEnumerable collection?

+6
source share
7 answers

I think you need a ForEach method;)

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

The problem is choosing whether to return a value, but also Linq is not intended to change collections. Think about choosing how to transform over the collection, rather than changing the state for each item.

Maybe the foreach loop is best suited here

+5
source

LINQ stands for Language INtegrated Query ... but you are not actually querying anything.

If mpwrapper.parser.Discoveries is a List<T> , you can use the ForEach method; or, if it's IEnumerable , you can always add a ForEach extension method ... but this is a more minor aesthetic change and has nothing to do with LINQ.

+4
source

If Discoveries is a list, then do it like

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

If not, convert it to a list first :)

0
source

The List<T>.ForEach does the trick.

However, this method does not exist on IEnumerable<T> .

0
source

Try the following:

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

I use a little trick using the .All method. It just requires a return boolean and presents very carefully. I included a sample with linq embedded inside .All

 configurations.All(c => { var gcx = globalConfigurations.FirstOrDefault(gc => gc.Type == c.Type && configurationGuids.Any(cGuid => gc.Guid == cGuid) ); return true; }); 
0
source

Source: https://habr.com/ru/post/949122/


All Articles