SBarnes wrote:But what I was simply doing was replicating the standard ToList functionality
I know. But I was reading about yield and iterator functions recently, so it was fairly fresh in my mind. I thought this would be a good place to share it, for people who haven't used it before to learn about it, since the conversation includes an example of how it would be useful.
If you're using LINQ (which Mike's original version does), then a function returning IEnumerable<T> will be considerably more efficient than creating a List<T> (which is an implementation of IEnumerable<T>), since FirstOrDefault<T> uses IEnumerable<T> as its input.
That said, replacing the bit of code that was breaking with a bit of code that uses an extension method; instead of:
- Code: Select all
JiwaFinancials.Jiwa.JiwaApplication.Notes.Note existingNote = Inventory.Notes.Cast<JiwaFinancials.Jiwa.JiwaApplication.Notes.Note>().FirstOrDefault(x => noteType != null && x.NoteType.RecID == noteType.RecID);
, it becomes
- Code: Select all
JiwaFinancials.Jiwa.JiwaApplication.Notes.Note existingNote = Inventory.Notes.ToEnumerable().FirstOrDefault(x => noteType != null && x.NoteType.RecID == noteType.RecID);
, although, since noteType == null will cause an exception to be thrown before this in the original code, one could just go with:
- Code: Select all
var existingNote = Inventory.Notes.ToEnumerable().FirstOrDefault(x => x.NoteType.RecID == noteType.RecID);
And when Jiwa adds IEnumerable(Of T) to JiwaCollection(Of T), then we should be able to do this:
- Code: Select all
var existingNote = Inventory.Notes.FirstOrDefault(x => x.NoteType.RecID == noteType.RecID);
SBarnes wrote:it would actually be good if the JiwaCollection supported both as built in.
I'm sure Mike will be reading this
.
Oh, and here's the VB version of the extension method:
- Code: Select all
<Extension()>
Public Iterator Function ToEnumerable(Of T)(collection As IJiwaCollection(Of T)) As IEnumerable(Of T)
For Each collectionItem As T In collection
Yield collectionItem
Next
End Function
and an example of wrapping VB.Collection (the underlying collection type in JiwaCollection) to implement IEnumerable(Of T)
- Code: Select all
Public Class Foo(Of T)
Implements IEnumerable(Of T)
Private _Collection As Microsoft.VisualBasic.Collection
Public Iterator Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
For Each collectionItem As T In _Collection
Yield collectionItem
Next
End Function
' required for IEnumerable(Of T)
Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return Me._Collection.GetEnumerator()
End Function
Public ReadOnly Property Collection As Microsoft.VisualBasic.Collection
Get
Return Me._Collection
End Get
End Property
End Class