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

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

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

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


当前回答

在解决方案中很可能已经定义了DataSet、DataTable和DataRow的类。如果是这样的话,就不需要DataSetExtensions引用了。

示例:数据集类名称-> CustomSet,数据流类名称-> CustomTableRow(定义列:RowNo,…)

var result = from myRow in myDataTable.Rows.OfType<CustomSet.CustomTableRow>()
             where myRow.RowNo == 1
             select myRow;

或者(随我喜欢)

var result = myDataTable.Rows.OfType<CustomSet.CustomTableRow>().Where(myRow => myRow.RowNo);

其他回答

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

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

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

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

VB。代码如下所示:

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

下面提供了如何实现这一目标的示例:

DataSet dataSet = new DataSet(); //Create a dataset
dataSet = _DataEntryDataLayer.ReadResults(); //Call to the dataLayer to return the data

//LINQ query on a DataTable
var dataList = dataSet.Tables["DataTable"]
              .AsEnumerable()
              .Select(i => new
              {
                 ID = i["ID"],
                 Name = i["Name"]
               }).ToList();

使用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();
//Create DataTable 
DataTable dt= new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
   new DataColumn("ID",typeof(System.Int32)),
   new DataColumn("Name",typeof(System.String))

});

//Fill with data

dt.Rows.Add(new Object[]{1,"Test1"});
dt.Rows.Add(new Object[]{2,"Test2"});

//Now  Query DataTable with linq
//To work with linq it should required our source implement IEnumerable interface.
//But DataTable not Implement IEnumerable interface
//So we call DataTable Extension method  i.e AsEnumerable() this will return EnumerableRowCollection<DataRow>


// Now Query DataTable to find Row whoes ID=1

DataRow drow = dt.AsEnumerable().Where(p=>p.Field<Int32>(0)==1).FirstOrDefault();
 //