C#LINQ使用where子句连接2个表

时间:2016-01-11 14:37:38

标签: c# linq

我在使用join子句进行过滤时尝试where 2个表。数据如下所示:

Category
Name Selected
A    0
B    1
C    0

SubCategory
Name ParentCategory Selected
s1   A              0
s2   B              1
s3   B              0

预期结果:

ParentCatName SubCatName SubCatSelected
B             s2         1
B             s3         0

实际结果:

ParentCatName SubCatName SubCatSelected
B             s2         1
B             s3         1  <-- should be 0

我使用的代码是:

IEnumerable<Category> result =
    from s in subcategories
    join c in categories
    on s.Parent equals c.Name into t
    from r in t.DefaultIfEmpty()
    where r == null ? false : r.Selected == true
    select new Category
    {
        Name = s.Name,
        Parent = (r == null ? string.Empty : r.Name),
        Selected = r.Selected
    };

编辑:帮助我明确的一点是暂时改写它以查看结果数据结构......

var result =
    from s in subcategories
    join c in categories
    on s.Parent equals c.Name into t
    from r in t.DefaultIfEmpty()
    select new
    {
        s, r
    };

然后我想出了过滤所选类别的答案。请参阅下面的答案..

4 个答案:

答案 0 :(得分:2)

不要过分复杂化。您要实现的目标是按所选类别过滤子类别。您可以使用以下简单查询获得所需结果

var result = from s in subcategories
             join c in categories on s.Parent equals c.Name
             where c.Selected
             select s;

答案 1 :(得分:1)

看起来你错了。如果r == null,则您将其设置为false,否则您将其设置为truer.Select == true

只需阅读您的查询,您可能根本不需要where条款。

可能想要这样的东西:

IEnumerable<Category> result =
    from s in subcategories
    join c in categories
    on s.Parent equals c.Name into t
    from r in t.DefaultIfEmpty()
    select new Category
    {
        Name = s.Name,
        Parent = (r == null ? string.Empty : r.Name),
        Selected = r.Selected
    };

或者,如果您需要进行null检查,请执行以下操作:

IEnumerable<Category> result =
    from s in subcategories
    join c in categories
    on s.Parent equals c.Name into t
    from r in t.DefaultIfEmpty()
    where r != null //I added the null check here
    select new Category
    {
        Name = s.Name,
        Parent = (r.Name), //I removed the null check here
        Selected = r.Selected
    };

答案 2 :(得分:0)

我认为,你的t值包含了categoies列表。 t必须包含子类别列表,然后您可以选择子类别的选定值。所以你总是得到选择的价值1 pls试试这个:

0     {'Ababua': 5, 'abandon': 7, 'abaction': 3, 'ab...
1     {'Aaronical': 3, 'abandon': 1, 'abaction': 4, ...
2     {'Aaronical': 5, 'Ababua': 1, 'abaction': 1, '...
3     {'Aaronical': 3, 'abandon': 1, 'abaction': 7, ...
4     {'Aaronical': 4, 'abandon': 2, 'abaction': 2, ...
OBS:我现在不试试这个。但我认为有效。

答案 3 :(得分:0)

好。所以我做了一些寻找并想出了这个......

IEnumerable<Category> result =
    from s in subcategories
    join c in categories.Where(f => f.Selected)
    on s.Parent equals c.Name into t
    from r in t.DefaultIfEmpty()
    where r == null ? false : true
    select new Category
    {
        Name = s.Name,
        Parent = s.Name,
        Selected = s.Selected,
    };

要将连接过滤到仅选定的父类别,我已将lambda表达式添加到该数据中。