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?
Just do the foreach . Or List<T>. ForEach() which is a method that is expected to have side effects (= state changes outside the method). As an aside, changing foreach loops to Linq just for the sake of it is one of the most common techniques to make code harder to understand and debug that I'm aware of in .
Why: You prefer to use LINQ syntax rather than a foreach loop. LINQ makes a query into a first-class language construct in C#. LINQ can reduce the amount of code in a file, make the code easier to read, and allow different data sources to have similar query expression patterns.
Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code. So your experience is that LINQ is faster and makes code harder to read and to maintain?
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
I think what you need is the ForEach method ;)
mpwrapper.parser.Discoveries.ToList().ForEach(s => { solution.AddFile("Discoveries", s.DisplayStringName + ".mpx", s); });
I use a little cheat with the .All method. It simply requires a return boolean value and presents very neatly. I included a sample with embeded linq inside the .All
configurations.All(c =>
{
var gcx = globalConfigurations.FirstOrDefault(gc =>
gc.Type == c.Type && configurationGuids.Any(cGuid => gc.Guid == cGuid)
);
return true;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With