更改linq查询以过滤许多次

时间:2014-03-16 08:31:40

标签: c# linq

我有以下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。

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

where a == c.Location.Name

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以尝试替换此部分:

where a == c.Location.Name

用这个:

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

如果Location媒体资源中的任何Locations Name等于a,则会返回true。