Reputation: 2179
I am seeking any advice or tips on the following method I have that is using LINQ to find a certain property in a Collection that is null and then go through the results (sub-list) and execute a method on another property from the same Collection.
private void SetRaises()
{
if (employeeCollection != null)
{
var noRaiseList = employeeCollection .Where(emp => emp.Raise == null).ToList();
foreach (var record in noRaiseList )
{
CalculateRaise(record);
}
}
}
public void CalculateRaise(Employee emp)
{
if (emp!= null)
emp.Raise = emp.YearsOfService * 100;
}
The part I don't like in the first method, SetRaises(), is the following snippet:
foreach (var record in noRaiseList )
{
CalculateRaise(record);
}
Is there a way to integrate that part into my LINQ expression directly, i.e. some extension method I am not aware of?
Thank you!
Upvotes: 2
Views: 145
Reputation: 4776
It should be something like this:
var noRaiseList = employeeCollection .Where(emp => emp.Raise == null).ToList().ForEach(e=>e.Raise = e.YearsOfService * 100);
Upvotes: 0
Reputation: 14432
You could use the ForEach chain-method. But that's only sugar syntax.
employeeCollection.Where(emp => emp.Raise == null)
.ToList()
.ForEach(record => CalculateRaise(record))
Upvotes: 0
Reputation: 17600
If you don't need list of employees without Raise you can do this in one line:
employeeCollection.Where(emp => emp.Raise == null).ToList().ForEach(x => x.Raise = x.YearsOfService * 100);
Upvotes: 0
Reputation: 1063058
The first thing you could do would be: don't generate an intermediate list:
var pending = employeeCollection.Where(emp => emp.Raise == null);
foreach (var record in pending)
{
CalculateRaise(record);
}
which is identical to:
foreach (var record in employeeCollection.Where(emp => emp.Raise == null))
{
CalculateRaise(record);
}
This is now non-buffered deferred execution.
But frankly, the LINQ here isn't giving you much. You could also just:
foreach(var emp in employeeCollection)
{
if(emp.Raise == null) CalculateRaise(emp);
}
Upvotes: 5