假设我们有:
public class Foo
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<Bar> { get; set; }
}
public class Bar
{
public long Id { get; set; }
public int Age { get; set; }
public virtual Foo { get; set; }
public long FooId { get; set; }
}
我们的数据可能看起来像这样:(假设 List<Foo>
)
// Forget the syntax, just to demonstrate data
foo[0] = new Foo{ Id = 1, Name = "A", Bar = { collection of Bars with Ages over 10 }};
foo[1] = new Foo{ Id = 2, Name = "B", Bar = { collection of Bars with Ages over 20 }};
foo[2] = new Foo{ Id = 3, Name = "C", Bar = { collection of Bars with Ages under 10 }};
现在,假设我想要所有这些 Foo
s 但与他们的 Bar
仅包括 Bar
年龄在 5-25 岁之间。
对于这样的事情,我会反向工作并获取所有 Bars,然后将所有关联的 Foos 获取到这些 bars,然后将 Bars 重新映射回 Foo。似乎过于复杂。
更清楚 - 所有 Foos 只有他们的 Bars 年龄在 5 到 25 岁之间 :)
最佳答案
如果要全选Foo
的,只有他们的 Bar
年龄在 5 到 25 岁之间:
var results =
from f in db.Foos
select new
{
f.Id,
f.Name,
Bars = f.Bars.Where(b => b.Age >= 5 && b.Age <= 25)
};
这将产生一个匿名类型作为结果。如果您需要创建命名类型(例如,如果您需要将函数的结果作为 List<T>
返回),您应该为此结果集创建一个简单的命名类型:
public class FooWithFilteredBarResult // replace with whatever name you like
{
public long Id { get; set; }
public string Name { get; set; }
public IEnumerable<Bar> { get; set; }
}
List<FooWithFilteredBarResult> results =
(from f in db.Foos
select new FooWithFilteredBarResult
{
Id = f.Id,
Name = f.Name,
Bars = f.Bars.Where(b => b.Age >= 5 && b.Age <= 25)
})
.ToList();
关于c# - 用于过滤实体集合列表并维护实体列表的 Linq 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18138875/