[英]join list with linq-to-sql query
I have list of MyObject that looks like this: 我有看起来像这样的MyObject列表:
public class MyObject{
public int FruitID {get;set;}
public string FruitName {get;set;}
}
List<MyObject> TheList = new List<MyObject>();
This list is populated with a linq-to-sql query. 此列表填充有linq-to-sql查询。 I'm looking to create a join between this list and a table that contains FruitID as its foreign key. 我正在寻找此列表和包含FruitID作为其外键的表之间的联接。
The table HarvestTimes looks like this: 表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
This is what I have so far: 这是我到目前为止的内容:
var TheQuery = (from list in TheList
join fruit in MyDC.HarvestTimes on
list.FruitID equals fruit.FruitID
where ....
select new MyObject{... }).ToList();
I'm have some trouble with the Where clause. 我对Where子句有些麻烦。 How do I get only the Fruit where the RipeFactor was always 2. For instance, Fruit 3 has a RipeFactor of 2 but also has 4 and whereas only Fruit4 has only 2s. 我如何只获得FruitFactor始终为2的水果。例如,水果3的RichFactor为2,但也有4,而只有Fruit4的只有2s。 I tried with Contains but both fruits come up. 我尝试了Contains,但是两种水果都出现了。
Thanks for your suggestions. 感谢您的建议。
Assuming there is a Relationship between the tables HaverstTime and Fruit: 假设表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);
This will create a IEnumerable<Fruit>
which I think can be easily converted to MyObject. 这将创建一个IEnumerable<Fruit>
,我认为它可以轻松转换为MyObject。
Update: Oops I forgot to add TheList.Select(q => q.FruitID). 更新:糟糕,我忘记添加TheList.Select(q => q.FruitID)。 That's why it didn't compile. 这就是为什么它没有编译的原因。 Sorry =) 对不起=)
Update2: Do the same, considering Ripefactor = 2 and 3 更新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);
I think this would work 我认为这会工作
var fruit = (from list in TheList
join fruit in
(from fr in MyDc.HarvestTimes
group fr by fr.FruitID into fg
where !fg.Any(f => f.RipeFactor != 2)
select fg)
on list.FruitID equals fruit.Key
select new MyObject{... }).ToList();
Update - If you only want to return the distinct list of FruitIDs you need to select fg.Key instead of fg 更新-如果您只想返回FruitID的唯一列表,则需要选择fg.Key而不是fg
var fruit = (from list in TheList
join fruit in
(from fr in MyDc.HarvestTimes
group fr by fr.FruitID into fg
where !fg.Any(f => f.RipeFactor != 2)
select fg.Key)
on list.FruitID equals fruit
select new MyObject{... }).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.