perplexedDev
perplexedDev

Reputation: 835

LINQ query to update property of a list

I am trying to convert the following code to linq:

 for (int i = 0; i < List.Count;i++ )
                {
                    List[i].IsActive = false;
                    if(List[i].TestList != null)
                    {
                        for(int j = 0;j<List[i].TestList.Count;j++)
                        {
                            List[i].TestList[j].IsActive = false;
                        }
                    }
                }

I tried the following query :

(from s in List select s).ToList().ForEach((s) =>
                        {
                            s.IsActive = false;
                            (from t in s.TestList where t != null select t).ToList().ForEach((t) =>
                                {
                                    t.IsActive = false;
                                });
                        });

But i get an error when TestList is null in the list. I am not sure what I am doing wrong here.

Upvotes: 0

Views: 152

Answers (4)

Fabio
Fabio

Reputation: 32445

If your original(no LINQ) code is worked.
Then you missed one line, which check for null of TestList before iterating items

(from s in List select s).ToList().ForEach((s) =>
    {
        s.IsActive = false;
        if(s.TestList != null) //This check of TestList was missing
            (from t in s.TestList where t != null select t).ToList().ForEach((t) =>
                        {
                                    t.IsActive = false;
                        });
    });

Upvotes: 1

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

You don't necessarily need an inner loop since it looks like you're deactivating all nested TestList items. You can just have two separate loops:

foreach(var item in List)
   item.IsActive = false;

foreach(var item in List.Where(x => x.TestList != null).SelectMany(x => x.TestList))
   item.IsActive = false;

Note that SelectMany "flattens" the inner lists into a single IEnumerable<T>.

Upvotes: 0

Ishtiaq
Ishtiaq

Reputation: 1058

A simple approach. No need to check for null.

 s.ForEach((x)=>
    {
        x.IsActive  = false;
        x.TestList.Foreach((t)=>{t.IsActive = false});

    });

Upvotes: 0

Joonas Koski
Joonas Koski

Reputation: 269

You are selecting lists that are null

where t == null 

Should the condition be

where t != null

Upvotes: 1

Related Questions