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.

1

3 Answers 3

8

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.";;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.