简体   繁体   中英

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.

 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. What I want is to select the option from sp.Options that matches the o.Option.Id. 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 is SPOptions class so I cannot pass it inside the contains method.

Search using Contains (sp.Options.Contains(o.Option.Id)) like:

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:

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.

Take a look at 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 :

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM