在 C# 中使用 lambda 获取嵌套列表中的特定元素

Get the specific element in nested list using lambda in c#

美好的日子,

假设我有一个静态 List<AClass> 对象(我们将其命名为 myStaticList),其中包含另一个列表,该列表包含另一个带有 CId 和名称的列表 属性.

我需要做的是

foreach(AClass a in myStaticList)
{
   foreach(BClass b in a.bList)
   {
      foreach(CClass c in b.cList)
      {
        if(c.CId == 12345)
        {
           c.Name = "Specific element in static list is now changed.";
        }
      }
   }
}

我可以使用 LINQ Lambda 表达式实现吗?

有点像;

myStaticList
.Where(a=>a.bList
.Where(b=>b.cList
.Where(c=>c.CId == 12345) != null) != null)
.something logical
.Name = "Specific element in static list is now changed.";

请注意,我想更改静态列表中该特定项目的 属性。

您需要 SelectMany 来展平您的列表:

var result = myStaticList.SelectMany(a=>a.bList)
                         .SelectMany(b => b.cList)
                         .FirstOrDefault(c => c.CId == 12345);

if(result != null)
    result.Name = "Specific element in static list is now changed.";;

使用SelectMany(优秀posthere

var element = myStaticList.SelectMany(a => a.bList)
                          .SelectMany(b => b.cList)
                          .FirstOrDefault(c => c.CId == 12345);

if (element != null )
  element.Name = "Specific element in static list is now changed.";
var item = (from a in myStaticList
           from b in a.bList
           from c in b.cList
           where c.CID = 12345
           select c).FirstOrDefault();
if (item != null)
{
    item.Property = "Something new";
}

您也可以使用 SelectMany,但这并不简单。