Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Subquery same Table

Tags:

c#

linq

I've a table with Id and CategoryId.

I need to get all records from that table with same CategoryId as the given Id.

This is what I came up to:

var query = from x in erm.Projects
            where x.CategoryId == erm.Projects.Where(y => y.Id == lookId).FirstOrDefault().CategoryId
            select x;

What's the best way to do this query?

Thank you

like image 743
DK ALT Avatar asked Jun 25 '26 00:06

DK ALT


1 Answers

You can use a join to do this sort of thing. Also has the advantage of avoiding a NullReferenceException if FirstOrDefault() returns null and you call .CategoryId on it blindly.

var query = erm.Table.Join(erm.Projects.Where(y => y.Id == lookId), x => x.CategoryId, y => y.CategoryId, (x,y) => x);
like image 97
Maverik Avatar answered Jun 26 '26 14:06

Maverik