无法将类型为“System.Collections.Generic.List”的对象转换为类型“System.Data.DataSet”

3

在对GridView进行排序时,我遇到了一个错误。我的数据源是一个名为results的变量,通过一个Linq查询获取得到。

protected void Page_Load(object sender, EventArgs e)
{
    dt1 = obj1.Table1data().Tables[0];
    dt2 = obj1.Table2data().Tables[0];
    dt3 = obj1.Table3data().Tables[0];

    var results = (
        from table1 in dt1.AsEnumerable()
        join table2 in dt2.AsEnumerable() on (int)table1["id"] equals (int)table2["id"]
        join table3 in dt3.AsEnumerable() on (int)table1["id"] equals (int)table3["id"]

        select new
        {
            id = (int)table1["id"],
            S1= (int)table1["S1"],
            P1= (double)table1["P1"],
            P2= (int)table2["P2"],
            P3= (double)table2["P3"],
            P4 = (int)table3["P4"],
            P5= (double)table3["P5"],

        }).ToList();

    Session["ds"] = results;
    GridView1.DataSource = results;
    GridView1.DataBind();
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataSet dataSet = (DataSet)Session["ds"];
    DataTable dataTable = dataSet.Tables[0];

    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }
}

// here in the GridView1_sorting at DataSet dataSet = (DataSet)Session["ds"], I am getting an error

错误:

Unable to cast object of type System.Collections.Generic.List`1[<>f__AnonymousType5`8[System.Int32,System.String,System.Int32,System.Double,System.Int32,System.Double,System.Int32,System.Double]]' to type 'System.Data.DataSet'

2) 另外一个问题,变量 results 的数据类型是什么。谢谢。Sun

1个回答

4
Session ["ds"]保存了变量results,而results是一个List<'A>的列表,其中'A是编译器生成的匿名类型。你不能将其强制转换为DataSet。如果你想将其放入会话中并在以后检索它,请声明一个适当的类,然后你可以轻松地将列表放入和从Session中取出。
我的意思是,你的查询正在构建一个匿名类型,因为有select语句。
 select new 
 {

一般情况下这是没问题的,但是如果您想在会话中使用此结果,则需要构建一个适当的类来保存该数据并赋予其正确的属性。

 public class MyData
 {
      // give it the appropriate properties you need
      public int ID { get; set; }
      public int S1 { get; set; }
      public double P1 { get; set; }
      public int P2 { get; set; }
      public double P3 { get; set; }
      public int P4 { get; set; }
      public double P5 { get; set; }
      // by the way... you should really come up with better names 
      // for these properties!
 }

然后进行查询。
 select new MyData
 {

当您调用ToList()并获得结果时,您将拥有List<MyData>。因此,当您从会话中检索它时,这就是您需要进行强制转换的内容。

 var list = (List<MyData>)Session["ds"];

嗨,感谢你的回复。但是你建议我如何进行排序?是否应该在列表上实现排序?我的意思是protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { var list = (List)Session["ds"];.... ..... }这些属性只是我为这篇文章随机命名的。 - user575219
您可以检查排序表达式,然后使用Linq的OrderBy方法进行构建。例如,var query = list.AsEnumerable(); if (e.SortExpression == "ID") { query = query.OrderBy(item => item.ID); } 搜索带有对象列表的网格视图以获取更多想法。 - Anthony Pegram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接