.net - "Cannot Resolve Symbol Select"尝试将 LINQ 与 DataRowCollection 一起使用

标签 .net linq

我正在尝试使用 LINQ 循环访问 DataTable 中的行,并根据列值实例化对象。棘手的代码如下所示。

问题是代码甚至无法编译。邪恶的错误消息是“无法解析符号选择”。

我很满意 DataRowCollection 实现 IEnumerable(它从 System.Data.InternalDataCollectionBase 获取它),因此您会认为以下内容没有问题(显然,我在这方面是错误的)。

我在我的项目中包含了 System.Linq System.Data 和 System.Data.SqlClient。它还具有所有必要的引用资料。我之前一直在整个应用程序中使用 LINQ(主要是使用 POCO 和 XDocuemnt 列表),这是我第一次看到这条特定消息。

有什么解决办法吗?

using (var command = connection.CreateCommand())
{
    command.CommandText = "dbo.sp_pTicklerContacts_sel_W_ContactRole_by_ComKey";
    command.CommandTimeout = 120;
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("@iComKey", SqlDbType.Int).Value = companyKey;

    using (var adapter = new SqlDataAdapter(command))
    {
        var dataset = new DataSet();
        adapter.Fill(dataset);
        if (dataset.TableCount() > 0 && dataset.Tables[0].Rows.Count > 0)
        {
            return (from row in dataset.Tables[0].Rows
                    select new TicklerContact
                               {
                                   CompanyKey = row.ToInt32("iTicklerContact"),
                                   Contact = row.ToString("ccontact"),
                                   ContactKey = row.ToInt32("iconkey"),
                                   TicklerContactKey = row.ToInt32("iTicklerContactKey"),
                                   Role = row.ToString("contactrole"),
                                   Exists = row.ToBool("contactexists")
                                 }).ToList();

        }
        return null;
    }
}

最佳答案

我认为您不能在 DataSet 行上使用 Linq,因为它没有实现 IEnumerable<T> .如果添加对 System.Data.DataSetExtensions 的引用对于您的项目,您可以使用扩展方法,它允许您:

 return (from row in dataset.Tables[0].AsEnumerable()
 ...

另请参阅之前关于 SO 的回答:LINQ query on a DataTable

来自 DataTableExtensions.AsEnumerable 的 msdn 文章:

Language-Integrated Query (LINQ) queries work on data sources that implement the IEnumerable interface or the IQueryable interface. The DataTable class does not implement either interface, so you must call the AsEnumerable method to use the DataTable as a source in the From clause of a LINQ query. You can also obtain custom, domain-specific operators, such as CopyToDataTable, by returning an IEnumerable object.

关于.net - "Cannot Resolve Symbol Select"尝试将 LINQ 与 DataRowCollection 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4672495/

相关文章:

.net - 从 Javascript 调用 Web 服务 - 它在幕后做了什么?

c# - 多层架构中的身份验证

c# - Linq 比较 C# 中的两个集合

c# - 通过对象中的 IDictionary<string,object> 属性选择不同记录

c# - 如何将相对路径转换为 ​​C#/.NET 中的完全限定路径?

c# - 如何在 Google Drive SDK 中获取文件修订的内容?

linq - 这个扩展方法是否有效地实现了我的 IQueryable?

c# - T-SQL 到 LINQ 的转换

c# - 如何将十六进制字符串转换为 byte[]

c# - EF - AND NOT EXISTS (SELECT 1 ...) with Entity Framework