【问题标题】:Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.List无法将类型“System.Linq.IQueryable<AnonymousType#1>”隐式转换为“System.Collections.Generic.List”
【发布时间】:2013-05-04 09:28:37
【问题描述】:

我是 .NET 世界的新手,我试图从 LINQ 获得一些结果。请帮忙。

以下是我得到的错误。

错误 4 无法将类型“System.Linq.IQueryable”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少演员表?)..Business\DAL\GlobalRequest.cs 39 27 Business

public ObservableCollection<AccountSummary> GetAccountSummary()
    {
        ObservableCollection<AccountSummary> list;
        list = from ListData in
                          (from a in dbc.Accounts
                           join b in dbc.Ledgers on a.Account_ID equals b.Account_ID into t2
                           from t2Data in t2.DefaultIfEmpty()
                           where a.Is_Mannual == Convert.ToChar("Y")

                           select new
                           {
                               Account_ID = a.Account_ID,
                               Account_Name = a.Account_Name,
                               Amount = t2Data.Amount == null ? 0 : t2Data.Amount
                           }
                        ).OrderBy(item => item.Account_Name)
                      group ListData by new
                      {
                          ListData.Account_ID,
                          ListData.Account_Name
                      } into GroupData
                      select new
                      {
                          Account_ID = GroupData.Key.Account_ID,
                          Account_Name = GroupData.Key.Account_Name,
                          Amount = GroupData.Sum(OL => OL.Amount)
                      };

    }

class AccountSummary
{
    public decimal AccountID { get; set; }
    public string AccountName { get; set; }
    public decimal Amount { get; set; }
}

请指教。

【问题讨论】:

    标签: wpf linq


    【解决方案1】:

    您的查询正在投射到匿名类型的集合(序列):

    select new
        {
            Account_ID = GroupData.Key.Account_ID,
            Account_Name = GroupData.Key.Account_Name,
            Amount = GroupData.Sum(OL => OL.Amount)
        };
    

    您需要投影到AccountSummary 的集合,例如:

    var accountSummaries = 
    
      ...rest of the query here
    
    select new AccountSummary
        {
            AccountId = ...,
            AccountName = ...,
            etc.
        };
    

    然后您可以从AccountSummary 的这个集合中创建您的 observable 集合:

    list = new ObservableCollection(accountSummaries);
    

    【讨论】:

    • 成功了,感谢您的帮助。大节省
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多