gpt4 book ai didi

c# - "Cannot convert lambda expression to type ' string ' because it is not a delegate type"在C#中查询数据集

转载 作者:太空狗 更新时间:2023-10-30 00:18:37 32 4
gpt4 key购买 nike

我有这段代码,它在 VB.NET 中编译得很好:

Imports System
Imports System.Data
Imports System.Data.Entity
Imports System.Data.SqlClient
Imports System.Linq
Imports System.Collections
Imports System.Collections.Generic

Friend Module MainModule
Friend Sub Main(args As String())
Dim ds = GetSqlDataSet("", "")
Dim allRows = From row In ds.Tables(0) Select row
End Sub

Private Function GetSqlDataSet(ByVal forQuery As String,
ByVal withConnectionString As String,
ByVal ParamArray withParameters As SqlClient.SqlParameter()) As DataSet

GetSqlDataSet = New DataSet()

Using conn As New System.Data.SqlClient.SqlConnection(withConnectionString)
Using command As New System.Data.SqlClient.SqlCommand(forQuery, conn)
command.Parameters.AddRange(withParameters)

Using dataAdaptor As New System.Data.SqlClient.SqlDataAdapter(command)
dataAdaptor.Fill(GetSqlDataSet)
End Using
End Using
End Using
End Function
End Module

引用资料如下:

enter image description here

现在我有了一个在 C# 中看起来完全等价的东西:

using System;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApplication1
{
internal static class MainEntryPoint
{
internal static void Main(string[] args)
{
var ds = GetSqlServerDataSet("", "");
var allRows = from row in ds.Tables[0] select row;
}

public static System.Data.DataSet GetSqlServerDataSet(string usingQuery,
string usingConnectionString, params System.Data.SqlClient.SqlParameter[] withParameters)

{
var ret = new System.Data.DataSet();

using (var conn = new System.Data.SqlClient.SqlConnection(usingConnectionString))
{
using (var command = new System.Data.SqlClient.SqlCommand(usingQuery, conn))
{
command.Parameters.AddRange(withParameters);

using (var adapter = new System.Data.SqlClient.SqlDataAdapter(command))
{
adapter.Fill(ret);
}
}
}

return ret;
}
}
}

引用文献如下:

enter image description here

但是我收到了这个错误:

enter image description here

我发现很多资源都提到了 adding a reference/using statements for System.Linqalso System.Data.Entity ,但显然我在这两种情况下都有。有人可以帮我解释一下吗?为什么它在 VB.NET 而不是 C# 中工作,我如何让它在 C# 中工作?

最佳答案

看起来 VB 内置了对 DataTable 的支持。这是一个简短但完整的示例:

Option Strict On

Imports System
Imports System.Data
Imports System.Linq

Public Class LinqTest

Shared Sub Main()
Dim table as DataTable = New DataTable
Dim allRows = From row In table Select row
End Sub

End Class

如果您对其进行编译,然后对其使用 ildasm,您会发现它会自动调用 DataTableExtensions.AsEnumerable()。我不想推测在 VB 中指定的位置,但它不是 C# 自动执行的操作的一部分。只需在您的 C# 代码中明确执行即可。

关于c# - "Cannot convert lambda expression to type ' string ' because it is not a delegate type"在C#中查询数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33784344/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com