我试图在数据表对象上执行LINQ查询,奇怪的是,我发现在数据表上执行这样的查询并不简单。例如:

var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;

这是不允许的。我怎么才能让这样的东西工作呢?

我很惊讶,LINQ查询不允许在数据表上!


当前回答

VB。代码如下所示:

Dim results = From myRow In myDataTable  
Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow

其他回答

使用LINQ操作数据集/数据表中的数据

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

正如@ch00k所说:

using System.Data; //needed for the extension methods to work

...

var results = 
    from myRow in myDataTable.Rows 
    where myRow.Field<int>("RowNo") == 1 
    select myRow; //select the thing you want, not the collection

您还需要向System.Data.DataSetExtensions添加一个项目引用

你不能查询DataTable的Rows集合,因为DataRowCollection没有实现IEnumerable<T>。您需要为DataTable使用AsEnumerable()扩展。像这样:

var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;

正如@Keith所说,您需要添加一个对System.Data.DataSetExtensions的引用

AsEnumerable()返回IEnumerable<DataRow>。如果你需要将IEnumerable<DataRow>转换为数据表,请使用CopyToDataTable()扩展。

下面是Lambda表达式查询,

var result = myDataTable
    .AsEnumerable()
    .Where(myRow => myRow.Field<int>("RowNo") == 1);

在我的应用程序中,我发现使用LINQ到数据集的AsEnumerable()扩展数据表,如答案中所建议的是非常慢的。如果你对优化速度感兴趣,可以使用James Newtonking的Json。网上图书馆(http://james.newtonking.com/json/help/index.html)

// Serialize the DataTable to a json string
string serializedTable = JsonConvert.SerializeObject(myDataTable);    
Jarray dataRows = Jarray.Parse(serializedTable);

// Run the LINQ query
List<JToken> results = (from row in dataRows
                    where (int) row["ans_key"] == 42
                    select row).ToList();

// If you need the results to be in a DataTable
string jsonResults = JsonConvert.SerializeObject(results);
DataTable resultsTable = JsonConvert.DeserializeObject<DataTable>(jsonResults);

这是一个简单的方法,适用于我和使用lambda表达式:

var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1)

然后如果你想要一个特定的值:

if(results != null) 
    var foo = results["ColName"].ToString()