More on the MSDN Enumerable Article
I finally worked out the details to fix the errors in the Enumerable article
on MSDN because of breaking changes in the .NET Framework 3.5 SP1 (thanks to Bob
Schild for pointing out the problem!)
In Part II of the article, replace Figure 6 with the following:
Dim items As New ArrayList
items.Add("January")
items.Add("August")
items.Add("October")
items.Add("April")
' Cast the ArrayList as a queryable group of strings
' (if the
cast to String failed for any element,
' this would raise an
exception):
Dim query = items.Cast(Of String)()
' Now, use the Enumerable class to query the data:
Dim results =
_
query.Where(Function(item) item.StartsWith("A"))
In Part II of the article, add the following paragraph, near the discussion
of the Enumerable.Cast method:
(The behavior of the Enumerable.Cast
method changed between the original version of Visual Studio 2008 and SP1.
Originally, the Cast method performed a conversion from the original type to the
type specified in the generic parameter. Starting in SP1, the Cast method
performs a cast, not a conversion. In other words, if the TryCast method would
return True in an attempt convert from the original type to the new type for
each element of the collection, the Cast method will succeed. The Cast method
triggers an exception when you execute the query if any element within the
collection can’t be implicitly cast to the new type.)
In the sample application, replace the CastDemo procedure with the
following:
Private Sub CastDemo(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Dim items As New ArrayList
items.Add("January")
items.Add("August")
items.Add("October")
items.Add("April")
' Cast the ArrayList as a queryable group of strings
' (if the
conversion to String failed for any element,
' this would raise an
exception):
Dim query As IEnumerable(Of String) = items.Cast(Of
String)()
' Now, use the Enumerable class to query the data:
Dim results =
_
query.Where(Function(item) item.StartsWith("A"))
DisplayResults(GetList(results))
End Sub
Replace the GetList and GetCommaList procedures:
Private Function GetList(ByVal items As IEnumerable) As String
Dim
newItems = From item In items Select value = item.ToString()
Return newItems.DefaultIfEmpty(). _
Aggregate(Function(current,
item) _
If(String.IsNullOrEmpty(current), _
item,
current & vbCrLf & item))
End Function
Private Function GetCommaList(ByVal items As IEnumerable) As String
' Convert the list into a list of strings:
Dim newItems = From item In
items Select value = item.ToString()
Return newItems.DefaultIfEmpty(). _
Aggregate(Function(current,
item) _
If(String.IsNullOrEmpty(current), _
item,
String.Format("{0}, {1}", current, item)))
End Function
Sorry for all the hassles--because of the long lead time, I hadn't even
considered installing SP1 (nor was I concerned that it would break code!) when I
wrote the article.