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

时间:2015-01-22 09:06:23

标签: c# linq lambda

好日子,

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

我需要做的是

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.";

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

3 个答案:

答案 0 :(得分:6)

您需要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.";;

答案 1 :(得分:3)

使用SelectMany(优秀帖子here

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.";

答案 2 :(得分:0)

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,但这并不简单。