LINQ query on a DataTable

前端 未结 23 1419
执笔经年
执笔经年 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:28
    var query = from p in dt.AsEnumerable()
                        where p.Field<string>("code") == this.txtCat.Text
                        select new
                        {
                            name = p.Field<string>("name"),
                            age= p.Field<int>("age")                         
                        };
    

    the name and age fields are now part of the query object and can be accessed like so: Console.WriteLine(query.name);

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

    Try this simple line of query:

    var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field<int>("RowNo") == 1);
    
    0 讨论(0)
  • 2020-11-22 02:28

    you can try this, but you must be sure the type of values for each Column

    List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){
         Property1 = (string)x.Field<string>("ColumnName1"),
         Property2 = (int)x.Field<int>("ColumnName2"),
         Property3 = (bool)x.Field<bool>("ColumnName3"),    
    });
    
    0 讨论(0)
  • 2020-11-22 02:29

    I realize this has been answered a few times over, but just to offer another approach:

    I like to use the .Cast<T>() method, it helps me maintain sanity in seeing the explicit type defined and deep down I think .AsEnumerable() calls it anyways:

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

    or

    var results = myDataTable.Rows.Cast<DataRow>()
                          .FirstOrDefault(x => x.Field<int>("RowNo") == 1);
    

    As noted in comments, no other assemblies needed as it's part of Linq (Reference)

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

    You can get it work elegant via linq like this:

    from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()
    where prod.Field<decimal>("UnitPrice") > 62.500M
    select prod
    

    Or like dynamic linq this (AsDynamic is called directly on DataSet):

    TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)
    

    I prefer the last approach while is is the most flexible. P.S.: Don't forget to connect System.Data.DataSetExtensions.dll reference

    0 讨论(0)
提交回复
热议问题