2016-07-11 88 views
0

所以以后有什么感觉好多头撞的,我有这个疑问:添加加入此LINQ查询?

var widgets = db.Updates 
     .Where(c => c.Sold.Equals(false)) 
     .GroupBy(c => c.widgetType)  
    .Select(x => x.OrderByDescending(y => y.TimeStamp).First()).ToList(); 
    widgetGrid.DataSource = widgets; 
    widgetGrid.DataBind(); 

现在,我把所有的销售的小工具,我需要添加一个加入,让我们说,例如,我要加入在所有者身份证上的“所有者”表ID等于身份证中的小部件,然后选择Owner.Name和Widget.Style

对于我的生活,我似乎没有任何地方快速...任何人?

一如既往......我非常感谢任何人的时间帮助我清理掉我的蜘蛛网。

+0

是这个EntityFramework?另外,向我们展示表格的定义。如果这是EntityFramework,那么在你的DbSet中,你应该在Widgets的Owners里设置一个List,并且你只需要db.Owners.Include(x => x.Updates).//获取你想要的东西。 – Dispersia

回答

0

如果我理解正确的话,你有两个序列:

  • 窗口小部件的序列,每个小部件都有一个属性Id。
  • 你有业主的序列,其中每个业主拥有物业编号

你想有一个匹配的ID序列和业主的组合。

顺便说一句,可能您的小部件将拥有一个ownerId或您的拥有者将有一个widgetId,但这不会影响解决方案。

的加入将是如下:

var joinedTable = widgets.join(owners, // join table widgets with table owners 
    w => w.Id     // from widgets take the Id 
    o => o.Id     // from owners also take the Id 
    (widget, owner) => new // where those Ids match, take the owner and the widget 
    {       // and take the properties you want 
     Id = widget.Id, 
     MyXProperty = owner.X, 
     MyYProperty = widget.Y, 

     Widget = widget,  // or take the complete widget and owner 
     Owner = owner, 
    }); 

顺便说一句,你写“现在,我有所有的卖小部件”。从你的代码段我明白每个更新都有一个布尔属性Sold,并且你希望所有的更新在哪里!已售出。我会假设你最终得到的是没有售出的物品?

谓词在where子句中的优点是什么。为什么不是这样:

var widgets = db.Updates.Where(c => !c.Sold) 
    .GroupBy // etc. 
0

你可以这样做:

var widgets = db.Updates 
     .Where(c => !c.Sold) 
     .GroupBy(c => c.widgetType)  
     .Select(x => x.OrderByDescending(y => y.TimeStamp).FirstOrDefault()); 

var result= (from w in widgets 
      join o in db.Owners on w.OwnerId equals o.Id 
      select new {o.Name, w.Style}).ToList(); 
+0

非常感谢大家,他们善待我的时间来帮助我!我相信所有的答案都可以工作,其中一些语法对我更有意义,并且可能会有性能差异,但无论哪种方式,我都非常感谢大家! – PaulBinCT2

0

,你也可以尝试:

var widgets = db.Updates 
     .Where(c => c.Sold.Equals(false)) 
     .GroupBy(c => c.widgetType)  
     .Select(x => x.OrderByDescending(y => y.TimeStamp).First()) 
     .Join(db.Owners, 
      u => u.ID, 
      o => o.ID, 
      (u, o) => new { o.Name, u.Style }).ToList();