LINQ query on a DataTable

前端 未结 23 1657
执笔经年
执笔经年 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: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 *
    

提交回复
热议问题