Reputation: 44342
How do I loop through a generic list and call a method based on a couple of conditions? I'd like to use linq syntax. The following doesn't work of course. Any ideas?
somelist.ForEach(i => i.DeptType == 1 && i != null () {MyMethod(someInt)});
If that isn't possible, what is the next best method using concise syntax?
Upvotes: 2
Views: 3199
Reputation: 110131
//standard style ... since Linq is Functional/side-effects-free
foreach(var x in somelist.Where(i => i != null && i.DeptType == 1))
{
SomeMethod(x);
}
//anon method style ... for those that must use ForEach
somelist.ForEach(i => {if (i != null && i.DeptType == 1) {MyMethod(someInt);}});
Upvotes: 4
Reputation: 307
I'd use:
somelist.Where(q => q !=null)
.Where(q => q.DeptType == 1)
.Select(q => MyMethod(q));
The resulting collection will contain a list of return values for the original values/method calls that were acted upon.
Upvotes: 0
Reputation: 1
One thing to keep in mind, you should make sure you do your null-checks before you access your object's fields, as in the following:
somelist.Where(i => i != null && i.DeptType == 1).ToList().ForEach( i=> MyMethod(i.someInt));
As someone above pointed out, you cannot call ForEach() on the Generic IEnumerable object returned from the Where() call. You must first call ToList() to save the results to a Generic List. I have updated the code above to include that change.
Upvotes: 0
Reputation: 54887
As appealing as one-liner LINQ queries may be, they’re typically associated with operations that do not have any side-effects (e.g. query projection, filtering, etc). In your case, you might be better served with a traditional foreach
loop:
foreach (var i in somelist)
if (i != null && i.DeptType == 1)
MyMethod(someInt);
P.S. Your original condition, i.DeptType == 1 && i != null
, is ordered incorrectly. The code will still give rise to a NullReferenceException
since i.DeptType
is executed before i
is null-checked.
Upvotes: 2
Reputation: 85056
Try using Where to specify which records you want to select and ForEach to execute your method:
somelist.Where(i => i.DeptType == 1 && i != null)
.ToList()
.ForEach( i=> MyMethod(i.someInt));
Upvotes: 6