c# - 用于过滤实体集合列表并维护实体列表的 Linq 表达式

标签 c# asp.net-mvc linq entity-framework

假设我们有:

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/

相关文章:

c# - 使用 linkedin 验证应用程序时出错

c# - 异步调用永远不会在 Asp.Net MVC 中返回

c# - 使用linq从输入文件中反转文本

c# - FileStream Read/Write 方法的限制

c# - WPF MVVM,我应该把 View 的特定属性放在哪里?

jQuery AJAX 请求 Controller 或服务作为代理?

c# - 使用 Moq .GetMock 向 Linq 表达式注册 ~1IRepository?

c# - LINQ 按日期分组 - 在不使用连接的情况下包括空天

c# - 无法将其转换为 VB.net

c# - Webforms vs Razor vs MVC 和工业用途