HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Iterating through a collection of objects

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
collectioniteratingobjectsthrough

Problem

Subject

I have to iterate through a collection of objects (in this case IGrouping). So I could do this easyly using a query with LINQ.

Code

public IEnumerable getParentPegs(IGrouping data)
    {
        IEnumerable 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 getParentPegs(IGrouping data)
    {
        List result = new List();

        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?

Solution

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 getParentPegs(IGrouping data) {

  List result = new List();

  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.

Code Snippets

public List<string> getParentPegs(IGrouping<string, SupplyDemand> data) {

  List<string> result = new List<string>();

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

  return result;
}

Context

StackExchange Code Review Q#9429, answer score: 3

Revisions (0)

No revisions yet.