我有一个类别列表(CategoryID’s(list CategoryID;此列表包含一些基于用户先前选择的id。
然后我有一个数据库,里面有可以成为一个或多个类别成员的公司。这是在联接表CompaniesInCategory中维护的,它会产生类似company的对象结构。类别。
现在我的问题是,我如何选择所有至少属于所选类别之一的公司。
List<int> categoryIds = new List<int>() {123, 3, 5858, 23};
List<company> companies = (from c in context.Companies
where c.Categories.(one of the Id's of these c.Categories should be in the list named categoryIds)
select c);
每个公司都有一个类别列表。从这个类别列表(c.categories((它们都有CategoryId(中,至少有一个必须与列表CategoryId中的一个id相匹配。
var companies = dc.Companies
.Where(c => c.Categories.Any(cat => categoryIds.Contains(cat.Id)))
"至少有一个">通常可以最好地转换为LINQ的Any()
方法。
似乎你在谈论这个:
var categoryIds=(new[] { 123, 3, 5858, 23 }).ToList();
var category=
new {
Id=123
};
var company=
new {
Categories=(new[] { category }).ToList()
};
var context=
new {
Companies=(new[] { company }).ToList()
};
var companies=(
from c in context.Companies
from x in c.Categories
from y in categoryIds
where x.Id==y
select c
).ToList();
因此,您指定的位置:
where c.Categories.(one of the Id's of these c.Categories should be in the list named categoryIds)
将是:
where c.Categories.Any(x => categoryIds.Contains(x.Id))
因为companies
等效于:
var companies=(
from c in context.Companies
where c.Categories.Any(x => categoryIds.Contains(x.Id))
select c
).ToList();
我不像以前那样熟悉理解语法,但假设类别字段名为CategoryId,我相信lambda版本是:
var companies = dc.Companies
.Where(c => categoryIds.Contains(c.CategoryId))
List<int> categoryIds = new List<int>() {123, 3, 5858, 23};
List<company> companies = (from c in context.Companies
where categoryIds.Contains(c.Categories)
select c).ToList(); //I would add .ToList() since List<company>
这应该工作
如果你的列表真的只有4点,那么你也可以做一些类似的事情
where c.Categories == 123 || c.Categories == 3 || //ect.
根据您的问题,我将再次检查(DB(类别表和类别列表。然后获取所有作为成员的公司是Category表。
List<int> categoryIds = new List<int>() {123, 3, 5858, 23};
List<company> companies = (from c in context.Companies
from b in context.Categories //Asuming there is a index table of some sort
where categoryIds.Contains(b.CatID) && c.companyID == b.companyID
select c).ToList();