Iterating through a collection of objects Subject

I have to iterate through a collection of objects (in this case IGrouping&lt;string, SupplyDemand&gt;). So I could do this easyly using a query with LINQ.

Code

    public IEnumerable&lt;string&gt; getParentPegs(IGrouping&lt;string, SupplyDemand&gt; data)
    {
        IEnumerable&lt;string&gt; 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&lt;string&gt; getParentPegs(IGrouping&lt;string, SupplyDemand&gt; data)
    {
        List&lt;string&gt; result = new List&lt;string&gt;();

        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?
You can do the same with just a foreach loop instead of reading the enumerator.

You can use the String.Compare method to do a case insensetive compare instead of creating a lowercase version of each string that you compare.

Improved improved code:

public List&lt;string&gt; getParentPegs(IGrouping&lt;string, SupplyDemand&gt; data) {

  List&lt;string&gt; result = new List&lt;string&gt;();

  foreach (SupplyDemand obj in data) {
    if (String.Compare(obj.Source, "make", true) == 0) {
      result.Add(obj.Peg);
    }
  }

  return result;
}


Note: In your first code you are getting the property Part, but in the second you are getting the property Peg instead.