【发布时间】:2017-05-18 08:38:09
【问题描述】:
我正在尝试将 C# 代码转换为 VB.Net,但无法在 Vb.NET 中找到与 C# 等效的解决方案产量返回
我正在遍历数据表。我发现的一种方法是使用 list 来遍历 Datatable 行。但同样需要将列表转换为数据表。那么在 VB.NET 中需要什么方法来生成返回数据表呢?
这是我的 VB.NET 代码:
Public Function GetFileData(ByVal sourceFileFullName As String, ByVal dt1 As System.Data.DataTable, ByVal RowCount As Integer) As IEnumerable(Of System.Data.DataTable)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings("con1").ConnectionString)
Dim chunkRowCount As Integer = 0
Dim Row As String
Using sr As StreamReader = New StreamReader(sourceFileFullName)
While Not (Row = sr.ReadLine()) = ""
If Not RowCount = 0 Then
chunkRowCount = chunkRowCount + 1
//var chunkDataTable = ; //Code for filling datatable or whatever
dt1.Rows.Add()
Dim i As Integer = 0
Dim Cell As String
For Each Cell in Row.Split(',')
If (String.IsNullOrEmpty(Cell)) Then
dt1.Rows(dt1.Rows.Count - 1)(i) = DBNull.Value
i = i + 1
ElseIf Cell = "00.00.0000" Then
dt1.Rows(dt1.Rows.Count - 1)(i) = DBNull.Value
i = i + 1
Else
dt1.Rows(dt1.Rows.Count - 1)(i) = Cell
i = i + 1
End If
Next
End If
RowCount = RowCount + 1
If chunkRowCount = 10000 Then
chunkRowCount = 0
Yield return dt1
dt1.Clear()
End If
End While
End Using
If dt1.Rows.Count > 0 Then
yield return dt1
End If
End Function
C#代码:
public static IEnumerable<System.Data.DataTable> GetFileData(string sourceFileFullName, System.Data.DataTable dt1, int RowCount)
{
var con = ConfigurationManager.ConnectionStrings["con1"].ConnectionString.ToString();
var connection = new SqlConnection(con);
int chunkRowCount = 0;
string Row;
using (var sr = new StreamReader(sourceFileFullName))
{
//Read and display lines from the file until the end of the file is reached.
while ((Row = sr.ReadLine()) != null)
{
if (RowCount != 0)
{
chunkRowCount++;
//var chunkDataTable = ; //Code for filling datatable or whatever
dt1.Rows.Add();
int i = 0;
foreach (string Cell in Row.Split(','))
{
if (String.IsNullOrEmpty(Cell))
{
dt1.Rows[dt1.Rows.Count - 1][i] = DBNull.Value;
i = i + 1;
}
else if (Cell == "00.00.0000")
{
dt1.Rows[dt1.Rows.Count - 1][i] = DBNull.Value;
i = i + 1;
}
else
{
dt1.Rows[dt1.Rows.Count - 1][i] = Cell;
i = i + 1;
}
}
}
RowCount = RowCount + 1;
if (chunkRowCount == 10000)
{
chunkRowCount = 0;
yield return dt1;
dt1.Clear(); // = null;
}
} //end while
}
//return last set of data which less then chunk size
if (dt1.Rows.Count > 0)
yield return dt1;
}
【问题讨论】:
-
你想做什么?您发布的代码尝试多次返回同一个表。一个已经可供调用者使用的表,因为它是调用者将其作为参数提供的。为什么在这种情况下返回任何东西?如果您必须返回某些东西,只需按原样返回表格即可
-
来自 Matteo Maqrciano:您可以在函数声明中使用 Iterator 修饰符,以便能够在 VB.NET 中使用 Yield
-
@PanagiotisKanavos,我只是想从 CSV 块中读取数据以避免 MemoryException 问题...对于数据表的每次迭代,它都会获取块集中的记录集并返回数据表跨度>
-
这不是这段代码的作用。它一遍又一遍地返回同一张表。此外,使用 ADO.NET 读取 CSV 可能是最昂贵的方式。