如何使用 lambda 从子集合中的对象获取值

How can I get value from object in sub-collection with lambda

我有这个代码:

class A
{ 
public string Prop1;
public string Prop2;
public List<B> Prop3;
}

class B
{ 
public string Value1;
public int Value2;
public double Value3;
}

并且有 A 列表,如果 B 中的 Value2 等于某个字符串,我需要从 B 中获取 Value1。我想使用 lambda。我怎样才能得到它?

这是我使用foreach时的代码:

//I have listA of type List<A>

foreach(var a in listA)
{
   foreach(bar b in a.Prop3
   {
      if(b.Value1=="some string")
      {
          return b.Value2;
      }
   }
}

如何在没有 foreach 的情况下使用 lambda?

我想你可以尝试使用任何

    var result=(from c in  listA where
 c.Prop3.Any(c=>c.Value2=="some string") select c.Prop3.Value1).ToList();
    foreach (B b in from a in listA from b in a.Prop3 where b.Value1=="some string" select b)
    {
        return b.Value2;
    }

你可以这样做:

 return listA
    .Select(a => 
        a.Prop3.FirstOrDefault(b => b.Value1 == "some string"))
    .FirstOrDefault();

我很想做这样的事情:

return listA.SelectMany(a => a.Prop3).FirstOrDefault(b => b.Value1 == "some string")?.Value2

要镜像您的代码,您可以使用这个:

return listA
    .SelectMany(x => x.Prop3)
    .Where(x => x.Value1 == "Some string")
    .Select(x => x.Value2)
    .FirstOrDefault();

我宁愿尝试获得正确的 B 和 return 其 Value2 如果找到的话:

B b = listA
    .SelectMany(x => x.Prop3)
    .FirstOrDefault(x => x.Value1 == "Some string");

return b != null
    ? b.Value2
    : string.Empty;