Search code examples
c#linq.net-2.0datatableasenumerable

c# using DataTable AsEnumerable() on .NET 2


I am trying to run the following code on a .net 2 winforms app:

DataTable dt = this.GetData(null, null, true, sql);

DateTime minDate = (from f in dt.AsEnumerable()
               select f.Field<DateTime>("Timestamp")).Min();

I am getting errors for the "using system.linq" and the ".AsEnumerable()". Is there any way I can resolve this to use AsEnumerable()? Or should I just abandon this method?

Thanks!


Solution

  • .NET 2 doesn't have LINQ. You could use LINQBridge, which may or may not include the AsEnumerable() extension method for DataTable. If it does, you can just use Cast<DataRow>() instead, optionally via an explicitly typed range variable:

    DateTime minDate = (from DataRow f in dt.AsEnumerable()
                        select f.Field<DateTime>("Timestamp")).Min();
    

    You'd then also need the Field<T> extension method on DataRow. You could probably write that yourself though, if it's not part of LINQBridge.

    Just to make it clear - none of this will work pleasantly if you're also using Visual Studio 2005, because you need the C# 3 features of lambda expressions, extension methods etc.

    Is there any possibility you could upgrade to .NET 3.5? It would make life a lot easier...