3

Good days,

Lets say I have a static List<AClass> object (lets name it myStaticList) which contains an other list inside and that list contains an other list with CId and Name property.

What I need to do is

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

Can I achieve this with LINQ Lambda expressions?

Something like;

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

Please note that i want to change the property of that specific item in the static list.

Valermus
  • 65
  • 1
  • 2
  • 4
  • possible duplicate of [Linq nested list expression](http://stackoverflow.com/questions/6144495/linq-nested-list-expression) – Paul Zahra Jan 22 '15 at 09:21

3 Answers3

7

You need SelectMany to flatten your lists:

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.";;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
3

Use SelectMany (excellent post 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.";
Community
  • 1
  • 1
Marko Juvančič
  • 5,792
  • 1
  • 25
  • 41
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";
}

You can use SelectMany also, but it's not straightforward.

qxg
  • 6,955
  • 1
  • 28
  • 36