0

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.

neobits
  • 108
  • 6
  • 7
    `foreach(var item in list.Skip(35))` ? – Irwene Sep 23 '22 at 12:45
  • 2
    `foreach` or a `for` loop with the correct starting index? – Ric Sep 23 '22 at 12:46
  • did you try `list.Skip(35).ToList()` ? This would create a new list where you can change property of all elements. – Sebastian Siemens Sep 23 '22 at 12:46
  • No actual piece of code used in production would (or rather should) have "index 35" hardcoded. Hopefully you have some other condition to select the elements to modify. – Jeroen Mostert Sep 23 '22 at 12:59
  • Sure, but that's out of scope of his question, so I understant giving a fixed value as an example. – Irwene Sep 23 '22 at 13:06
  • @JeroenMostert that's true, my list should take at a given moment, the top down 50% of those customers and mark them as unblocked or `isBlocked = false` – neobits Sep 23 '22 at 13:15

3 Answers3

3

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;
}
gunr2171
  • 16,104
  • 25
  • 61
  • 88
0

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).

neobits
  • 108
  • 6
  • 1
    of course it uses a foreach loop, how else would you enumerate the collection? – Ric Sep 23 '22 at 13:13
  • @gunr2171 ah, I was thinking about a `ForEach` for `IEnumerable`, since creating a new list is rather unnecessary. And *that* is not packaged with LINQ, even if it is [common to add it yourself](https://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet). – JonasH Sep 23 '22 at 14:04
0

You can also do it with a "for" loop

for(var i = 35; i < storeCustomers.Count() - 35; i++)
{
    storeCustomers[i] = false;
}