Is using linq in this situation overkill
c#, linq
Solution
The ToList method is an extension method used with LINQ, but the ForEach method is just a method in the List class.
The major overhead here is the call to the ToList method, which creates a new List from the collection. The ForEach also has a slight overhead as it has to call a delegate for each item.
If you want to use LINQ methods, the Aggregate method seems more appropriate:
public int GetIncrementTotal() {
return m_items.Aggregate(0, (t, i) => t + i.GetIncrement());
}
Or Sum:
public int GetIncrementTotal() {
return m_items.Sum(i => i.GetIncrement());
}
Either has a slight overhead over your original version, so if you want the most efficient, just stick to a simple loop.
Problem
I am thinking about a re-factor, but I don't know if the end result is just overkill. Currently I have ``` IList<myobjecttypebase> m_items; public int GetIncrementTotal() { int incrementTot; foreach(myobjecttypebase x in m_items) { incrementTot += x.GetIncrement(); } } ``` Would it be overkill and/or less efficient to use linq for the ForEach ``` m_items.ToList().ForEach(x => incrementTot += x.GetIncrement()); ``` Would the cast be a significant overhead here?