List transactions
Posted
Fri, Dec 19 2008 0:55
by
bill
From a recent discussion on using lists, and whether or not you can remove items in while iterating, I decided to write an extension that allows you to get a “transaction” for an IList(Of t). This ListTransaction(Of T) caches adds and removes until you call commit (kudos to Duncan for the idea !!). It also implements IDisposable so you can use a using scope, eg:
Using listTran = mylist.GetTransaction
For Each item In mylist
' other code here
listTran.Remove(item)
Next
End Using
And here’s the implementation:
Module ListExtensions
<Runtime.CompilerServices.Extension()> _
Function GetTransaction(Of T)(ByVal list As IList(Of T)) As ListTransaction(Of T)
Return New ListTransaction(Of T)(list)
End Function
Public Class ListTransaction(Of T)
Implements IDisposable
Private _list As IList(Of T)
Private _adds As List(Of T)
Private _removes As List(Of T)
Public Sub New(ByVal list As IList(Of T))
_list = list
End Sub
Public Sub Add(ByVal item As T)
If _adds Is Nothing Then _adds = New List(Of T)
_adds.Add(item)
End Sub
Public Sub Remove(ByVal item As T)
If _removes Is Nothing Then _removes = New List(Of T)
_removes.Add(item)
End Sub
Public Sub Commit()
If _list Is Nothing Then Exit Sub
If _adds IsNot Nothing Then
For Each item As T In _adds
_list.Add(item)
Next
_adds = Nothing
End If
If _removes IsNot Nothing Then
For Each item As T In _removes
_list.Remove(item)
Next
_removes = Nothing
End If
End Sub
Public Sub Rollback()
_adds = Nothing
_removes = Nothing
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Commit()
GC.SuppressFinalize(Me)
End Sub
End Class
End Module