Update item in IEnumerable

Linq is for querying, not updating. Linq queries return a new collection (or an itearator on top of the source collection) based on projections, filters etc. So your choices are:

  • Save the “new” collection back to the variable (or a new variable, if necessary):

      allsubdirs = allsubdirs.Select(a => a + "_" + DateTime.Now.ToString("hhmmss")).ToList();
    
  • Use a writable interface like IList<T> and a for loop:

      IList<string> allsubdirs = new List<string>() { "a", "b", "c" };
    
      for(int i=0; i<allsubdirs.Count; i++)
          allsubdirs[i] = allsubdirs[i] + "_" + DateTime.Now.ToString("hhmmss");
    

The main difference is that Select does not modify the original collection, while the for loop does.

My opinion is that the Select is cleaner and is not “cheating” – you’re just adding a projection on top of the original collection.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)