LINQ结果到C#中的数据集:无法将AnonymousType强制转换为DataSet

时间:2013-11-10 20:13:57

标签: c# linq dataset

我想获取结果并将其转换为Dataset。我的代码是:

var res = 
    from i in dbconnect.tblManageDates
    where i.internationalCode == _international
    select new
    {
        i.companyId,
        i.endDate,
        i.startDate,
        i.dateId
    };

_result = (DataSet)res;

当我将其提取到Dataset时,我收到此错误:

  

无法投射类型的对象   'System.Data.Linq.DataQuery 1[<>f__AnonymousType0 4 [System.String,System.String,System.String,System.Int32]]'   输入'System.Data.DataSet'。

1 个答案:

答案 0 :(得分:1)

尝试使用此类扩展程序:

public static class Extesions
{
    public static DataSet ToDataSet<T>(this IList<T> list)
    {
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        ds.Tables.Add(t);

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

            t.Columns.Add(propInfo.Name, ColType);
        }

        //go through each property on T and add each value to the table
        foreach (T item in list)
        {
            DataRow row = t.NewRow();

            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }

            t.Rows.Add(row);
        }

        return ds;
    }
}

用法:

public class Entity
{
    public int CompanyId { get; set; }
    public DateTime EndDate { get; set; }
    public DateTime StartDate { get; set; }
    public int DateId { get; set; }
}

// ...

List<Entity> res = dbconnect.tblManageDates.Where(i => i.internationalCode == _international).Select(i => new Entity
{
    CompanyId = i.companyId,
    EndDate = i.endDate,
    StartDate = i.startDate,
    DateId = i.dateId
}).ToList();

DataSet dataSet = res.ToDataSet();