0

我有一个类别列表(CategoryID's) List categoryIds; 此列表包含一些基于用户先前选择的 id。

然后我有一个数据库,其中包含可以成为一个或多个类别成员的公司。这是在连接表 CompaniesInCategory 中维护的,这会产生像 company.Categories 这样的对象结构。

现在我的问题是,我如何选择至少属于所选类别之一的所有公司。

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)中,至少有一个必须与列表 categoryIds 中的一个 id 匹配。

4

5 回答 5

1
var companies = dc.Companies
    .Where(c => c.Categories.Any(cat => categoryIds.Contains(cat.Id)))

“至少一个”通常最好地转化为 LINQ 的Any()方法。

于 2013-01-07T02:24:27.847 回答
1

似乎你在谈论这个:

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();
于 2013-01-07T02:29:21.330 回答
0
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.
于 2013-01-07T00:54:27.353 回答
0

我不像以前那样熟悉理解语法,但假设类别字段名为CategoryId,我相信 lambda 版本是:

var companies = dc.Companies
    .Where(c => categoryIds.Contains(c.CategoryId))
于 2013-01-07T00:57:37.080 回答
0

据我了解您的问题,我应该检查(DB)类别表与类别列表。然后获取所有成员公司是类别表。

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();
于 2013-01-07T02:16:56.517 回答