2015-10-16 127 views
1
public static IQueryable<ProBE> GetAllPol() 
     { 
      ConnectionString CS = new ConnectionString(); 
      var pol = (from pol in CS.pols 
          select new ProBE 
          { 
           Id = pol.Id, 
           Name = pol.Name, 
           Weight = pol.Weight, 
           EnID = pol.EnID, 
           PolID = pol.PolID 
          }).GroupBy(c=>c.PolID).Take(1); 
      return pol; 
     } 

上面是我的代码,它绑定到Devexpress网格。我将在的CS.pols表中在DB中有2个或更多的条目。我想按PolID分组,因为只有这个字段在各个版本中保持不变。我想group by it和take 1。我收到一个错误,说不能将IQueryAble转换为ProBE。请帮助我如何获得所需的数据。按asp.net中的类对象进行分组并取其中1个mvc

回答

1

你的第一个问题,因为你在做末尾GroupBy它将返回IEnumerable<IGrouping<T>>,所以永远不会转换为IQueryable<ProBE>。所以你需要先对它进行分组,然后进行相同的设计。

接下来的问题是Take,它返回IEumerable<T>但你组合,这样使用FirstOrDefault代替后只需要第一项: -

var pol = (from pol in CS.pols 
      group pol by pol.PolID into g 
      let firstgroupedPol = g.OrderByDescending(x => x.Id).FirstOrDefault() 
      select new ProBE 
       { 
        Id = firstgroupedPol != null ? firstgroupedPol.Id : 0, 
        Name = firstgroupedPol != null ? firstgroupedPol.Name : "", 
        //similarily others 
        PolID = g.Key 
       }); 
+0

Tahnks它的工作。但是我有两个不同版本的单个名称的记录。我想要我可以通过Id(最新的主键)获得的最新版本。我怎样才能做到这一点。现在您提供的解决方案首先给我(旧版本记录)。请帮忙。 – user2998990

+0

@ user2998990 - 您可以简单地按ID降序排列。检查我的更新。 –

+1

你是一个拯救生命的拉胡尔。万分感谢 – user2998990

相关问题