Subject
I have to iterate through a collection of objects (in this case IGrouping<string, SupplyDemand>
). So I could do this easyly using a query with LINQ.
Code
public IEnumerable<string> getParentPegs(IGrouping<string, SupplyDemand> data)
{
IEnumerable<string> query =
from d in data
where d.Source.ToLower() == "make"
select d.Part;
return query;
}
Problem
I'm using this function inside a loop in a VSTO Excel project and it's pretty slow, besides it stops running (memory leak). So I came up with the following code:
Improved Code
public List<string> getParentPegs(IGrouping<string, SupplyDemand> data)
{
List<string> result = new List<string>();
var enumerator = data.GetEnumerator();
while (enumerator.MoveNext())
{
SupplyDemand obj = enumerator.Current;
if (obj.Source.ToLower() == "make")
{
result.Add(obj.Peg);
}
}
return result;
}
Question
Is there any other way to improve this?
var pegs = getParentPegs(....); int count = pegs.Count(); foreach(var peg in pegs){ // Doing something else here }
Will cause your expression to be evaluated twice, whereas the improved code will only evaluate it once. You can overcome this by forcing it to evaluate and store it in a list by calling the .ToList() method: var pegs = getParentPegs(...).ToList(); Or return a List within getParentPegs. \$\endgroup\$