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

时间:2013-08-09 01:32:01

标签: 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 }};

现在,我想说我希望所有FooBar,但Bar只包含一个年龄介于5-25之间的{{1}}。

对于这样的事情,我会反向工作并得到所有的条形图,然后将所有关联的Foos都放到那些条形图上,并将条形图重新映射回Foo。似乎过于复杂。

更清楚 - 只有年龄在5到25之间的酒吧的所有Foos :)

3 个答案:

答案 0 :(得分:4)

如果您想要在5到25岁之间选择所有Foo和仅Bar

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();

答案 1 :(得分:1)

var r = Foos.Select(x => new Foo()
        {
            Id = x.Id,
            Name = x.Name,
            Bars = x.Bars.Where(y => y.Age <= 25 && y.Age >= 5).ToList()
        });

答案 2 :(得分:1)

这也只会选择独特的Foo。

bars.Where(b => b.Age >= 5 && b.Age <= 25).GroupBy(b => b.FooId).Select(g => g.FirstOrDefault().Foo).ToList();