linq anon对象利用父对象属性和子对象属性

时间:2014-12-10 17:42:47

标签: c# linq

我在使用父类和子类相关类的属性构建一个匿名对象时遇到了困难(这可能不是正确的术语,所以如果我错了请纠正我)

假设:

public class Foo
{
    public int UserId { get; set; }
    public List<Bar> Bars { get; set; }
}

public class Bar
{
    public string SomeProperty { get; set; }
    public string SomePropertyINeedToUpdate { get; set; }
}

我正在尝试创建一个由Foo.UserId和Foo.Bars.SomeProperty组成的匿名对象(每个列表项Bar.SomeProperty和Foo.UserId组合的一个对象)

这是我到目前为止所做的,但不确定如何从两个对象中拉出1个/多个 - 还可以看到

中的模拟对象

https://dotnetfiddle.net/FFO5x7

   // Here I can get Foo information, but unsure how to get bar
   var items =
      from f in this.Foos
      select new 
      {
         UserId = f.UserId
         SomeProperty = null// how to get Bar.SomeProperty?
      };

   // Here I can get Bar information, but unsure how to get Foo
   var items =
      from b in this.Foos.SelectMany(sm => sm.Bars)
      select new 
      {
         UserId = null // how to get Foo.UserId?
         SomeProperty = b.SomeProperty 
      };

鉴于来自小提琴的数据,我想要的是anon对象:

{ 1, "test" },
{ 1, "Other Test" },
{ 2, "Blah Test" },
{ 2, "Blah Other test" }

2 个答案:

答案 0 :(得分:2)

您需要执行以下操作

var items = from f in this.Foos
            from b in f.Bars
            select new
            {
                UserId = f.UserId,
                SomeProperty = b.SomeProperty
            };

答案 1 :(得分:1)

您似乎在寻找SelectMany的{​​{3}}:

this.Foos.SelectMany(sm => sm.Bars, 
           (f,s) => new { UserId = f.Id, SomeProperty = s.SomeProperty });