如何到处不能使用两个查询枚举多次

时间:2013-11-22 22:00:33

标签: c#

以下代码在第二个ToList()上抛出“无法枚举多次”。修复此错误的最佳方法是什么?

var firstQuery = (from r in db.SomeProcedure(Id)
                       select new MyClass
                       {
                            Id = r.Id,
                            Name = r.Name,
                            Company= r.Company,
                            Title = r.Title
                       });

        var secondQuery = (from d in firstQuery
                          group d by d.Title into groupedTitles
                         select new MyClass2
                         {                                 
                             Title = groupedTitles.Key,  //How To include the Id                                  
                         });

          List<MyClass> mClass = firstQuery.ToList();
          Th Below ToList() is throwing a cannot enumerate more than one
          List<MyClass2> mClass2 = secondQuery.ToList();

如何解决错误?

1 个答案:

答案 0 :(得分:0)

立即将您的第一个查询转换为列表。

var firstQuery = (from r in db.SomeProcedure(Id)
                   select new MyClass
                   {
                        Id = r.Id,
                        Name = r.Name,
                        Company= r.Company,
                        Title = r.Title
                   }).ToList();

    var secondQuery = (from d in firstQuery
                      group d by d.Title into groupedTitles
                     select new MyClass2
                     {                                 
                         Title = groupedTitles.Key,  //How To include the Id                                  
                     });

      List<MyClass> mClass = firstQuery;
      List<MyClass2> mClass2 = secondQuery.ToList();