nidarshani fernando
nidarshani fernando

Reputation: 533

If and else with LINQ

I have a class structure like in the following,

class class_A
{
    public bool isChecked;
    public int id;        
}

class class_B
{
    List<class_A> classAObjects=new List<class_A>();
}

class class_C
{
    List<class_B> classBObjects=new List<class_B>();
}

and have a list of objects created from class_C,

List<class_C> classCObjects=new List<class_C>();

I want to assign true or false to class_A.isChecked for each instance of class_A based on some condition. If the ID is 100, then it should assign false. Otherwise, it should assign true.

Here is my code right now:

classCObjects.ToList().ForEach(a=>a.classBObjects.ForEach(b=>b.classAObjects.ForEach(x=>x.isChecked=true)));

The above assign true to all. Does anyone know how to get what I need?

Upvotes: 0

Views: 65

Answers (2)

John Saunders
John Saunders

Reputation: 161773

classCObjects.ToList()
             .ForEach(a=>a.classBObjects
                 .ForEach(b=>b.classAObjects
                     .ForEach(x=>x.isChecked=x.id != 100)));

By the way, it's ugly to call ToList on a collection just so you can use ForEach. Instead, just iterate:

foreach (var a in classCObjects) {
    foreach (var b in a.classBObjects) {
        foreach (var x in b.classAObjects) {
            x.isChecked = x.id != 100;
        }
    }
}

Upvotes: 5

Peyman
Peyman

Reputation: 3138

Are you looking for something like this?

classCObjects.ToList().ForEach(
   a=>a.classBObjects.ForEach(
     b=>b.classAObjects.ForEach(
       x=>x.isChecked= x.id != 100)));

Upvotes: 1

Related Questions