2

I have a List of different DayTime (Ticks). I try to get a list of the time remaining from now to each time element.

List<long> diffliste = new List<long>(m_DummyAtTime);

// 864000000000 ≙ 24h
diffliste.ForEach(item => { item -= now; if (item < 0) item += 864000000000; }); 

// test, does also not work
// diffliste.ForEach(item => { item -= 500; }); 

However, the list is not changed. Do I miss something? (now is DateTime.Now.TimeOfDay.Ticks)

ccellar
  • 10,326
  • 2
  • 38
  • 56
Nikodemus RIP
  • 1,369
  • 13
  • 20

4 Answers4

2
var times = diffliste.Select(ticks => new DateTime(ticks) - DateTime.Now);

Will return a collection of TimeSpans between now and each time.

Without using Linq:

List<TimeSpan> spans = diffliste.ConvertAll(ticks => new DateTime(ticks) - DateTime.Now);

(modified as suggested by Marc)

vc 74
  • 37,131
  • 7
  • 73
  • 89
1

You are changing a standalone copy in a local variable (well, parameter actually), not the actual value in the list. To do that, perhaps:

for(int i = 0 ; i < diffliste.Count ; i++) {
    long val = diffliste[i]; // copy the value out from the list
    ... change it
    diffliste[i] = val; // update the value in the list
}

Ultimately, your current code is semantically similar to:

long firstVal = diffliste[0];
firstVal = 42;

which also does not change the first value in the list to 42 (it only changes the local variable).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You cannot change the value of an item inside a foreach cycle.
You can do it using a classic for cycle or creating and assigning items to a new list.

for (int i = 0 ; i < diffliste.Count; i++) 
{
    long value = diffliste[i];
    // Do here what you need
    diffliste[i] = value;
}
Marco
  • 56,740
  • 14
  • 129
  • 152
0

The iteration var in a foreach cycle is immutable, so you cannot change it. You either have to create a new list or use a for cycle... see also here.

Community
  • 1
  • 1
mamoo
  • 8,156
  • 2
  • 28
  • 38
  • 1
    The OP is not using `foreach`, they are using `ForEach` - while similar, this exposes the value as a parameter to a delegate, which *is* mutable... it just doesn't change the underlying value in the list in any way – Marc Gravell Nov 24 '11 at 10:10