c# - 使用 linq-to-sql 查询加入列表

标签 c# linq

我有如下所示的 MyObject 列表:

public class MyObject{
  public int FruitID {get;set;}
  public string FruitName {get;set;}
}

List<MyObject> TheList = new List<MyObject>();

此列表填充有 linq-to-sql 查询。我希望在此列表和包含 FruitID 作为其外键的表之间创建连接。

HarvestTimes 表如下所示:

FruitID   |   HarvestDatetime  |   RipeFactor
   3      |        3/4/2011    |       2
   3      |        4/5/2011    |       4
   3      |        5/5/2011    |       3
   4      |        3/21/2011   |       2
   4      |        4/10/2011   |       2
   4      |        5/10/2011   |       2

这是我目前所拥有的:

var TheQuery = (from list in TheList
                join fruit in MyDC.HarvestTimes on
                list.FruitID equals fruit.FruitID
                where ....
                select new MyObject{... }).ToList();

我在使用 Where 子句时遇到了一些麻烦。 我如何只获得 RipeFactor 始终为 2 的 Fruit。例如,Fruit 3 的 RipeFactor 为 2,但也有 4,而只有 Fruit4 只有 2s。我尝试使用 Contains,但两种水果都出现了。

感谢您的建议。

最佳答案

假设表 HaverstTime 和 Fruit 之间存在关系:

var TheQuery = MyDC.HarvestTimes
    .Where(p => TheList.Select(q => q.FruitID).Contains(p.FruitID))
    .GroupBy(p => p.Fruit)
    .Where(p => p.All(q => q.RipeFactor == 2))
    .Select(p => p.Key);

这将创建一个 IEnumerable<Fruit>我认为它可以很容易地转换为 MyObject。

更新: 糟糕,我忘了添加 TheList.Select(q => q.FruitID)。这就是它没有编译的原因。 抱歉 =)

更新2: 做同样的事情,考虑 Ripefactor = 2 和 3

var TheQuery = MyDC.HarvestTimes
    .Where(p => TheList.Select(q => q.FruitID).Contains(p.FruitID))
    .GroupBy(p => p.Fruit)
    .Where(p => p.All(q => q.RipeFactor == 2 || q.RipeFactor == 3))
    .Select(p => p.Key);

关于c# - 使用 linq-to-sql 查询加入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5967168/

相关文章:

c# - 如何在 vb.net 中实现值类型的 C# 'as' 关键字?

c# - 使用存储过程时,不能多次枚举查询结果

c# - 使用C#通过div中的内容获取div类

c# - 如何在 Unity 中为刚体对象制作动画

vb.net - LINQ All 和 Any 复杂对象

c# - 将 XML 中的后代查询到 Linq

c# - WPF 数据网格绑定(bind)错误?

c# - 处理 'Sequence has no elements' 异常

asp.net - 匿名类型列表

c# - 使用 LINQ 嵌套查询获取更新的最新行