Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the magic of LINQ - How to call a delegate for each criteria that matches?

Tags:

lambda

linq

I wanna do something like this:

List<string> list = new List<string>();
... put some data in it ...

list.CallActionForEachMatch(x=>x.StartsWith("a"), ()=> Console.WriteLine(x + " matches!"););

Syntax: CallActionForEachMatch(Criteria, Action)

How is this possible? :)

like image 840
Rookian Avatar asked Dec 09 '22 18:12

Rookian


1 Answers

I wouldn't; I'd just use:

foreach(var item in list.Where(x=>x.StartsWith("a"))) {
    Console.WriteLine(item + " matches!");
}

But you could use:

list.FindAll(x=>x.StartsWith("a"))
    .ForEach(item=>Console.WriteLine(item + " matches!"));
like image 163
Marc Gravell Avatar answered Jun 04 '23 20:06

Marc Gravell