5

I have a collection of objects representing a folder structure.

I'd like to set the property FileExtension to null, if it's a folder.

This is as far as I've got. Can anyone help?

var items = MyClass.All().ToList();
items.ForEach(x => x.FileExtension = string.empty)
     .Where(y => y.FileExtension == "folder")
     .ToList();
Gilles 'SO- stop being evil'
  • 98,216
  • 36
  • 202
  • 244

2 Answers2

7
items
  .Where(i => i.FileExtension == "folder")
  .ToList()
  .ForEach(i => i.FileExtension = null);
Amy B
  • 105,294
  • 20
  • 131
  • 182
  • I was trying to use just linq - so perfect! Thank you –  Sep 15 '09 at 08:31
  • To be picky, ToList() is not linq; it's a generics list method. Still, this seems to be an acceptable way to do it, even with the crowd that argues against having a foreach in linq. http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet, and http://stackoverflow.com/questions/101265/why-is-there-not-a-foreach-extension-method-on-the-ienumerable-interface. The cleanest with no side-effects tends to be the good ol' foreach loop, as with @TcKs answer. – goodeye Jun 27 '12 at 01:41
  • More picky: System.Linq.Enumerable.ToList – Amy B Jun 27 '12 at 03:40
  • Shoot, sorry, miswrote - and yes, since I was being picky - it's the ForEach that's not linq, it's a generics list method. That's what I meant, yeah, that. – goodeye Jun 28 '12 at 22:09
6
foreach(var item in items.Where( i => i.FileExtension == "folder" ))
    item.FileExtension = null;
BFree
  • 100,265
  • 20
  • 154
  • 199
TcKs
  • 24,801
  • 9
  • 64
  • 97