【问题标题】:Changing a linq query to filter on many-many更改 linq 查询以过滤多对多
【发布时间】:2014-03-16 08:31:39
【问题描述】:

我有以下 Linq 查询

public static List<string> selectedLocations = new List<string>();

// I then populate selectedLocations with a number of difference strings, each
// corresponding to a valid Location

viewModel.people = (from c in db.People
                    select c)
                    .OrderBy(x => x.Name)
                    .ToList();

// Here I'm basically filtering my dataset to include Locations from
// my array of selectedLocations

viewModel.people = from c in viewModel.people
                    where (
                    from a in selectedLocations
                    where a == c.Location.Name
                    select a
                    ).Any()
                    select c;

这非常有效,因为每个 Person 记录都可以有一个 Location。

我的问题是,如果 Person 可以与 Location 建立一对多关系,我该如何更改此查询?以一个人可以有 2 个位置为例,我需要将此行更改为什么?

where a == c.Location.Name

谢谢!

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    你可以尝试更换这部分:

    where a == c.Location.Name
    

    有了这个:

    where c.Locations.Any(o => o.Name == a)
    

    如果Locations 属性中的任何Location 具有Name 等于a,则返回true。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多