Reputation: 519
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
Upvotes: 1
Views: 280
Reputation: 1416
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.
Upvotes: 1
Reputation: 26426
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();
Upvotes: 0
Reputation: 20757
If BOCollection implements IEnumerable, then you've already got the iterator goodness. Just throw it in a for or foreach loop.
Upvotes: 0