LINQ query on a DataTable

前端 未结 23 1381
执笔经年
执笔经年 2020-11-22 01:59

I\'m trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:

相关标签:
23条回答
  • 2020-11-22 02:11

    For VB.NET The code will look like this:

    Dim results = From myRow In myDataTable  
    Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow
    
    0 讨论(0)
  • 2020-11-22 02:12

    As @ch00k said:

    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
    

    You also need to add a project reference to System.Data.DataSetExtensions

    0 讨论(0)
  • 2020-11-22 02:15

    This is a simple way that works for me and uses lambda expressions:

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

    Then if you want a particular value:

    if(results != null) 
        var foo = results["ColName"].ToString()
    
    0 讨论(0)
  • 2020-11-22 02:16
    var results = from DataRow myRow in myDataTable.Rows
        where (int)myRow["RowNo"] == 1
        select myRow
    
    0 讨论(0)
  • 2020-11-22 02:17

    You can use LINQ to objects on the Rows collection, like so:

    var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;
    
    0 讨论(0)
  • 2020-11-22 02:20

    I propose following solution:

    DataView view = new DataView(myDataTable); 
    view.RowFilter = "RowNo = 1";
    DataTable results = view.ToTable(true);
    

    Looking at the DataView Documentation, the first thing we can see is this:

    Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.

    What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to "query" against the DataTable.

    Here is how this works in this particular case:

    You try to implement the SQL Statement

    SELECT *
    FROM myDataTable
    WHERE RowNo = 1
    

    in "DataTable language". In C# we would read it like this:

    FROM myDataTable
    WHERE RowNo = 1
    SELECT *
    

    which looks in C# like this:

    DataView view = new DataView(myDataTable);  //FROM myDataTable
    view.RowFilter = "RowNo = 1";  //WHERE RowNo = 1
    DataTable results = view.ToTable(true);  //SELECT *
    
    0 讨论(0)
提交回复
热议问题