Convert Dataset to IQueryable<T> or IEnumerable<T>

33,338

Solution 1

table.AsEnumerable()...

table.AsEnumerable().AsQueryable()...

However, you'd need to write your own translation (Select) to your type; and the IQueryable<T> would still be using LINQ-to-Objects; the only purpose (in this scenario) of using IQueryable<T> over IEnumerable<T> would be to use expressions for some other reason - perhaps for the dynamic LINQ library.

Solution 2

you can use something like this.

DataSet ds = GetData();
DataTable dt= ds.Tables[0];
var query =
    from row in dt.AsEnumerable() 
    select new IMyData()
    {
        property1= row[0],
        property2= row[1]
    };
Share:
33,338
jlembke
Author by

jlembke

Consultant developer for a large manufacturing company.

Updated on July 09, 2022

Comments

  • jlembke
    jlembke almost 2 years

    Since there is no Linq to DB2 yet (c'mon IBM!), and I want to deal with IQueryables or IEnumerables in my code, how would I convert a DataTable to an IQueryable? Or an IEnumerable?

    I have an interface and a class that matches the columns in the datatable...

    IQueryable<IMyData> GetAS400Data(..parameters..)
    {
        DataSet d = GetData();
        ...
        //Some code to convert d to IQueryable<IMyData>
    }
    

    DataTable.Rows does not support .AsQueryable, since MSFT yanked it, so I'm not sure what to do here.

  • jlembke
    jlembke over 15 years
    Unfortunately, due to a bad experience last year, EF has been ruled out for me. That's unfortunate, since EF is MSFT's future...
  • MattSlay
    MattSlay about 15 years
    How do you convert the other way? From IQueryable to a DataTable?
  • Marc Gravell
    Marc Gravell about 15 years
    The IQueryable<T> is essentially a view over the data. The original DataTable still remains. To create a DataTable, perhaps see this: stackoverflow.com/questions/545328/…
  • Rami Sarieddine
    Rami Sarieddine over 11 years
    @MarcGravell could elaborate please on how to do the translation ? i tried IQueryable<T> resultList =(DataSet.Tables[0]).AsEnumerable().AsQueryable(); i got an error: can not convert type IQueryable<DataRow> to type IQueryable<T>.
  • Christian
    Christian about 3 years
    Change job then :)