[英]LINQ Query comparing Id with an Id in a list inside SingleOrDefault query
I am trying to fetch an option using the SingleOrDefault Linq to SQL method. 我正在尝试使用SingleOrDefault Linq to SQL方法获取一个选项。
var po = repository.Context.AsQueryable<Option>().SingleOrDefault(o => o.Option.Id == sp.Options // sp.Options is a collection);
The problem is that inside the SingleOrDefault method I am comparing p.Option.Id == a collection. 问题是在SingleOrDefault方法内部,我正在比较p.Option.Id ==集合。 What I want is to select the option from sp.Options that matches the o.Option.Id.
我想要的是从与o.Option.Id匹配的sp.Options中选择选项。 How can I do that?
我怎样才能做到这一点?
UPDATE: One thing I should have mentioned that the sp.Options is a different class than the Option class. 更新:我应该提到的一件事是sp.Options是与Option类不同的类。 sp.Options is SPOptions class so I cannot pass it inside the contains method.
sp.Options是SPOptions类,因此无法在contains方法内传递它。
Search using Contains
(sp.Options.Contains(o.Option.Id))
like: 使用
Contains
(sp.Options.Contains(o.Option.Id))
例如:
var po = repository.Context.AsQueryable<Option>()
.SingleOrDefault(o => sp.Options.Contains(o.Option.Id));
If members of sp.Options
are different from Id
then you can do: 如果
sp.Options
成员与Id
不同,则可以执行以下操作:
var po = repository.Context.AsQueryable<Option>()
.SingleOrDefault(o => sp.Options.Any(r=> r.Id == o.Option.Id));
or 要么
var po = repository.Context.AsQueryable<Option>()
.SingleOrDefault(o => sp.Options.Select(r=> r.Id).Contains(o.Option.Id));
Assuming Id
is the field in sp.Options
elements that you want to compare with. 假定
Id
是要与之比较的sp.Options
元素中的字段。
Take a look at Contains . 看一下Contains 。
repository.Context.AsQueryable<Option>().SingleOrDefault(o => sp.Options.Contains(o.Option.Id));
If Options is not a collection of the class of Option.Id, you can use the Any method with your comparison logic in it as follow : 如果Options不是Option.Id类的集合,则可以将Any方法与比较逻辑一起使用,如下所示:
repository.Context.AsQueryable<Option>().SingleOrDefault(o => sp.Options.Any(opts => opts.Something == o.Option.Id));
Based on your question it seems you're expecting to have a single match between those two option sets, correct ? 根据您的问题,您似乎希望这两个选项集具有单个匹配项,对吗? If so, I'd suggest you to write it as:
如果是这样,我建议您将其编写为:
var po = repository.Context.AsQueryable().Where(o => sp.Options.Any(item=>item.id == o.Option.Id)).SingleOrDefault(); var po = repository.Context.AsQueryable()。Where(o => sp.Options.Any(item => item.id == o.Option.Id))。SingleOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.