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'
  • 104,111
  • 38
  • 209
  • 254

2 Answers2

7
items
  .Where(i => i.FileExtension == "folder")
  .ToList()
  .ForEach(i => i.FileExtension = null);
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • 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 <-- if it "is not Linq", why's it in a Linq namespace, huh huh? – 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
  • 102,548
  • 21
  • 159
  • 201
TcKs
  • 25,849
  • 11
  • 66
  • 104