The result of calling:
db.Books.Select(a => new { a.Title,a.Author})
is an
IEnumerable<anonymous-type>
. There is no built-in conversion operator to turn that into a
DataSet
.
Fortunately, it's not too hard to write one yourself:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
namespace YourNamespace
{
public static class Extensions
{
public static DataTable ToDataTable<T>(this IEnumerable<T> source, string tableName = null)
{
if (source == null) throw new ArgumentNullException("source");
var properties = TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.ToList();
var result = new DataTable(tableName);
result.BeginInit();
foreach (var prop in properties)
{
result.Columns.Add(prop.Name, prop.PropertyType);
}
result.EndInit();
result.BeginLoadData();
foreach (T item in source)
{
object[] values = properties.Select(p => p.GetValue(item)).ToArray();
result.Rows.Add(values);
}
result.EndLoadData();
return result;
}
public static DataSet ToDataSet<T>(this IEnumerable<T> source, string dataSetName = null, string tableName = null)
{
if (source == null) throw new ArgumentNullException("source");
if (string.IsNullOrEmpty(dataSetName)) dataSetName = "NewDataSet";
var result = new DataSet(dataSetName);
result.Tables.Add(source.ToDataTable(tableName));
return result;
}
}
}
With that extension method in place, you should then be able to call:
stiReport1.RegData(db.Books.Select(a => new { a.Title, a.Author }).ToDataSet());