Search code examples
c#linqcollections

How to update values in a collection List<int> in other collection LINQ


This works:

data.ForEach(x =>
{
    x.ClientIds = new List<int> { 111 };
});

return data;

But I don't want to create a new object, I just want to update the list like:

data.ForEach(x =>
{
    x.ClientIds.Select(v => { v = (int)sandboxClientId; return v; });
});

return data;

But in this second approach, my data.ClientIds still has old value. Why?

What will be the best approach to update this collection?


Solution

  • If ClientIds is a List<int> your 2nd approach doesn't work because you don't assign a list, you call a method that returns a value that is not used, you are not modifying anything.

    So all integers should have the same value? Since int is a value type you cannot change it without assigning a new. So all you could do is to replace all items in the list via indexer. Maybe this simple extension would be useful(also for other use-cases):

    public static class Extensions
    {
        public static void ReplaceAllListValues<T>(this IList<T> list, T newValue, Predicate<T>? replaceIf = null)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (replaceIf == null || replaceIf(list[i]))
                {
                    list[i] = newValue;
                }
            }
        }
    }
    

    Now your code becomes:

    data.ForEach(d => d.ClientIds.ReplaceAllListValues((int)sandboxClientId));