Search code examples
c#linqgroup-byasenumerable

LINQ object of IEnumerable type does not return a DataTable


Could someone briefly me explain why the I cannot use the CopyToDataTable method on the following linq object (of IEnumurable type)?

var query = from r in SourceData.AsEnumerable()
        group r by r["fruitid"] into Dt
        select new
        {
        Group = Dt.Key,
        Sum = Dt.Sum((t)=> double.Parse(t["name"].ToString())) 
        };

Reminder: My aim consists of retrieving the resulting DataTable following the GroupBy Clause


Solution

  • There is a restriction on the generic type of CopyToDataTable.

    Take a look at the declaration of the method:

    public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
        where T : DataRow
    {
    
    }
    

    If you notice that second line, your IEnumerable<T> must be an enumerable of DataRows. What you have is an enumerable of anonymous objects.

    Depending on what your DataTable is coming from, bound to, etc, there are many other ways to accomplish what you're trying to do, but this is why you don't have that method available.