【问题标题】:Get the specific element in nested list using lambda in c#在c#中使用lambda获取嵌套列表中的特定元素
【发布时间】:2015-03-21 00:13:52
【问题描述】:

好日子,

假设我有一个静态 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.";

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

【问题讨论】:

标签: c# linq lambda


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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,但这并不简单。

      【讨论】:

        猜你喜欢
        • 2021-09-19
        • 1970-01-01
        • 2015-10-15
        • 1970-01-01
        • 2019-08-12
        • 2023-02-04
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        相关资源
        最近更新 更多