Home > Net >  Modify all elements from a List<T> starting at an index
Modify all elements from a List<T> starting at an index

Time:09-24

I have a List<MemberData> storeCustomers with the following type in C#,

public class MemberData
{
   public string clientId;
   public string displayName;
   public bool isBlocked;
}

Let's say my list has 100 members with different clientId and displayName, but all have the same isBlocked = true. If I want to change the same field starting at the index 35 until the end, for isBlocked = false, how do I do it? I want to keep the same List and avoid truncating.

CodePudding user response:

You'll need to use a for or foreach loop, because you need to cause side effects to your list.

You can use the Skip Linq method to ignore all entries before the given index. Then process the entries as normal.

foreach (var entry in yourList.Skip(35))
{
    entry.isBlocked = false;
}

CodePudding user response:

I have found a way, but it appears not to be optimized as it uses a ForEach.

So using System.Linq,

int skipIndex = 35;
storeCustomers.Skip(skipIndex).ToList().ForEach(x => x.isBlocked = true);

Is there's a faster and more performant way to do this task? (probably no using Threading of course).

  • Related