0

我想获取我的结果并将其转换为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__AnonymousType04[System.String,System.String,System.String,System.Int32]]”类型的对象转换为“System.Data.DataSet”类型。

4

1 回答 1

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();
于 2013-11-10T20:47:35.267 回答