tags:

views:

156

answers:

3

I have this code snippet where we get a collection from COM Dll

 public BOCollection SelectedObjects{
get
{
    IMSICDPInterfacesLib.IJMonikerElements oIJMonikerElements;
    oIJMonikerElements = m_oIJSelectSet.Elements as IMSICDPInterfacesLib.IJMonikerElements;
    BOCollection oBusinessObjects = new BOCollection(oIJMonikerElements);
    return oBusinessObjects;
}

}

Now BOCollection does implement IEnumerable. So would it be better to change it to

public IEnumerable<BusinessObject> SelectedObjects

So as to get the iterator goodness ? Or is there another way ?

thanks Sunit

A: 

If BOCollection implements IEnumerable, then you've already got the iterator goodness. Just throw it in a for or foreach loop.

Chris Doggett
A: 

The problem with IEnumerable<T> is yes, it will give you "Linq goodness", but the lowest common denominator of Linq goodness. Better to return IList<T> or even IQueryable<T> (if you can do this).

For example if somebody wanted to get the 4th element, IEnumerable<T> doesn't makes sense if you are already storing the objects in an array or list.

To get IQueryable<T> from a List<T> do this:

IQueryable<int> query = list.AsQueryable();
Keltex
+1  A: 

Are you wanting to return IEnumerable so you get deferred execution? First off, you wouldn't want to do this in a property, as I'm sure FxCop will yell at you for that. Here's how I suggest you change things so you can benefit from both deferred execution and LINQ.

Change the m_oIJSelectSet.Elements property to a method that returns IEnumerable like so:

public IEnumerable<IJMonikeElements> GetElements() {
    // Do some magic here to determine which elements are selected
    return (from e in this.allElements where e.IsSelected select e).AsEnumerable();

//  This could also be a complicated loop
//  while (someCondition()) {
//      bool isSelected = false;
//      var item = this.allItems[i++];

        // Complicated logic determine if item is selected
//      if (isSelected) {
//          yield return item;
//      }
    }
}

public IEnumerable<BusinessObject> GetSelectedObjects() {
    return m_oIJSelectSet.GetElements().Cast<BusinessObject>();
}

Now, you'll have complete deferred execution and LINQ support.

mnero0429
No control over the SelectSet. It's returned by a service as an interfaceIJSelectSet m_oIJSelectSet = (IJSelectSet)oIJDTrader.get_Service("SelectSet", "");I can only cast it to IJMonikerElements as shown earlier. In that case, since BOCollection does implement IEnumerable<T>, not much to change !
Sunit
Ah, I apologize, I thought that that by "Now BOCollection does implement IEnumerable" you meant the non-generic version of the interface, in which case you don't get much "LINQ Goodness". As an aside, FxCop will yell at your for returning a collection from a property. It's bad practice.
mnero0429