Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace foreach loop with linq

Tags:

c#

linq

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?

like image 820
TOP KEK Avatar asked Jul 10 '13 13:07

TOP KEK


People also ask

How do I replace foreach loops?

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 .

What can I use instead of foreach in C#?

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.

Which is better foreach or LINQ?

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?

What is faster than foreach C#?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


2 Answers

I think what you need is the ForEach method ;)

mpwrapper.parser.Discoveries.ToList().ForEach(s => { solution.AddFile("Discoveries", s.DisplayStringName + ".mpx", s); });
like image 150
dotixx Avatar answered Oct 18 '22 22:10

dotixx


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;
});
like image 26
Leon van Wyk Avatar answered Oct 18 '22 23:10

Leon van Wyk