Search code examples
c#listselectsubtraction

How to subtract a property value from a list on a condition


In my C# application, I need to subtract a property value from a huge list (HoList? Right now i do this, not sure i so it right?

int value1 =2;
HoList.Select(r => r.Count - value1).ToList();

Solution

  • In your question you're taking HoList which is some type with a property Count. I can see that by looking at the Select statement.

    When you call Select you are choosing what you want to return and in your example you're returning Count - value1. This is most likely an int result. Select is just returning an IEnumerable<int> and then ToList() is turning that IEnumerable<int> to a List<int>. You're also not assigning that list to anything.

    If you want to alter the original list you can do something like this:

    HoList.ForEach(r => r.Count -= value1);
    

    If it's a large list you can utilize parallelism for something like this also:

    HoList.AsParallel().ForAll(r => r.Count -= value1);