【问题标题】:converting query from IList to object将查询从 IList 转换为对象
【发布时间】:2010-11-01 00:42:44
【问题描述】:

我是 c# 的新手,在将 IList 分配给查询后尝试访问它时遇到问题。这是我的代码:

System.Collections.IList Invoices =
     (from p in entities.InvoiceCards
      where (p.CustomerCard.ID == CustomerID)
      select new
      {
         InvoiceID = p.ID,
         InvoiceDatetime = p.DateTime,
         InvoiceTotal = (decimal) p.InvoiceTotal,
      }).ToList();

// update the grid
invoiceCardDataGridView.DataSource = Invoices;

----------- 这里编译器在抱怨对象 c?如何在不再次执行查询的情况下访问 IList 中的对象?我需要使用 IList 作为数据源。什么是更好的方法?请附上代码

foreach (var c in Invoices)
    InvoiceTotal += (decimal)c.InvoiceTotal;

【问题讨论】:

标签: c#


【解决方案1】:

您在查询中使用匿名类型的问题。 因此,当您获得这种匿名类型的 IList 并分配给数据源时,默认情况下您将失去其类型。

当您想在代码的另一部分从 DataSource 中检索它时,您必须使用适当的类型对其进行强制转换。由于匿名类型是由编译器生成的,因此您将无法强制转换它。

一种解决方案是创建包含该类型的类(如果不存在)。

public class InvoicePart
{
   public int InvoiceID {get; set}
   public DateTime InvoiceDatetime {get; set}
   public decimal InvoiceTotal {get; set}
}

现在您可以修改查询以获取类型列表

List<InvoicePart> Invoices =
     (from p in entities.InvoiceCards
      where (p.CustomerCard.ID == CustomerID)
      select new InvoicePart
      {
         InvoiceID = p.ID,
         InvoiceDatetime = p.DateTime,
         InvoiceTotal = (decimal) p.InvoiceTotal,
      }).ToList();

// update the grid
invoiceCardDataGridView.DataSource = Invoices;

当您获得数据时,您会将其转换为列表

List<InvoicePart> Invoices = (List<InvoicePart>)invoiceCardDataGridView.DataSource;

foreach (InvoicePart c in Invoices)
{
    invoiceTotal += c.InvoiceTotal;
}

【讨论】:

  • 请注意这个关键句:“我需要使用IList 来用作数据源。”我认为这是IList 的强类型版本不是一个选项(请注意IList&lt;T&gt; 不是IList)。
  • 我注意到了,我注意到他是 c# 的新手。所以我试图解释使用 IList 的替代方法
【解决方案2】:

如果列表包含匿名类型,并且foreach 循环在第一个代码块之外的其他方法中,则不能那样使用它。

请查看this post,这可能对您的情况有所帮助。

【讨论】:

    【解决方案3】:

    如果您绝对必须使用IList,那么您最好定义显式类型而不是使用匿名类型。然后,当您需要使用它们时,您必须将 IList 的元素转换为您的显式类型。

    【讨论】:

      【解决方案4】:

      Zied 有解决这个问题的正确想法。但是请注意,绑定到List&lt;T&gt; 不是双向的(对列表的更改不会反映在网格中)。为此,您需要使用BindingSource:

      List<InvoicePart> Invoices =
           (from p in entities.InvoiceCards
            where (p.CustomerCard.ID == CustomerID)
            select ...
      
      // update the grid
      var bs = new BindingSource();
      bs.DataSource = Invoices;
      invoiceCardDataGridView.DataSource = bs;
      

      【讨论】:

      • 没问题。考虑支持对您有帮助的答案并接受对您最有帮助的答案(我投票给 Zied)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 2014-12-30
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多