3

I'm trying to use the following loop

foreach (Form frm in this.MdiChildren)
{
    frm.Close();
}

and transcribe it into a Linq expression like so:

this.MdiParent.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Close());

but this line shows me a NullReferenceException "Object reference not set to an instance of an object"

What am I doing wrong? I am a newbie in Linq.

greg dorian
  • 136
  • 1
  • 3
  • 14
  • Which object is giving you a nullreferenceexception? – Kenneth Apr 18 '13 at 22:49
  • 2
    Although it saves a line (or three), I would go for the non Linq variant because it's more easy to understand. – Michel Keijzers Apr 18 '13 at 23:10
  • This generally isn't the type of thing you should use LINQ for. It's more ubiquitous and readable in the foreach form. – Kendall Frey Apr 19 '13 at 00:07
  • There is no advantage in using LINQ to do this because each command must be executed in sequence. You can't benefit from any parallelization. Yeah, and then there's the fact that it's unreadable. – Cody Gray - on strike Apr 19 '13 at 03:07
  • thanks for your comments, but affects the performance? and yes it would be to save some lines. since I mentioned previously, also I am learning to use linq (newbie), I'm in process of understanding it!. – greg dorian Apr 19 '13 at 13:30

1 Answers1

5

Try this:

this.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Close());

Unless you are trying that code from one of the children, in which case you try your code

this.MdiParent.MdiChildren.OfType<Form>().ToList().ForEach(x => x.Close());

and it should also work.

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75