Jeff Jeff - 1 year ago 118 Question

Convert LinQ code from C# code to VB.Net

How do I rewrite this code as Online conversion tools gag when it tries to convert the Return part of the functions.

private static DataColumn[] ParseColumns(string tableHtml)
MatchCollection headerMatches = Regex.Matches(

return (from Match headerMatch in headerMatches
select new DataColumn(headerMatch.Groups[1].ToString())).ToArray();

private static DataColumn[] GenerateColumns(MatchCollection rowMatches)
int columnCount = Regex.Matches(

return (from index in Enumerable.Range(0, columnCount)
select new DataColumn("Column " + Convert.ToString(index))).ToArray();

Specifically, the online tools will give me something like this:

Private Shared Function GenerateColumns(rowMatches As MatchCollection) As DataColumn()
Dim columnCount As Integer = Regex.Matches(rowMatches(0).ToString(), CellPattern, ExpressionOptions).Count

Return (From index In Enumerable.Range(0, columnCount)New DataColumn("Column " + Convert.ToString(index))).ToArray() End Function

Its this last part that is incorrect:

(From index In Enumerable.Range(0, columnCount)New DataColumn("Column " + Convert.ToString(index))).ToArray()

and I don't understand what this C# code is trying to do -- it looks like LINQ or something like that.


Answer Source

That is LINQ code. The great thing about it is that it is entirely syntactic sugar for a chain of method calls. The from is used to introduce a loop variable (effectively) from an enumerable, and the select generates a result. The latter actually corresponds to a method Select(). You can rewrite the C# LINQ code as follows:

Enumerable.Range(0, columnCount).Select(index => new DataColumn("Column " + index)).ToArray();

This creates an array of DataColumn objects, one for each number from 0 to the given columnCount. You can use basically the same syntax in VB, except the lambda will look a little different:

Enumerable.Range(0, columnCount).Select(Function(index) New DataColumn("Column " & index)).ToArray()

I assume that's all you needed help with.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download