Idea for a Foreach extension

  • Thread starter Thread starter Josh Ferguson
  • Start date Start date
J

Josh Ferguson

I don't believe a syntax driven equivalent exists for this, but I just
thought it would be neat if you could use foreach to do something like this:

foreach (Object x in collection1, collection2)

and have it sequentially enumerate through both of them.
 
Josh Ferguson said:
I don't believe a syntax driven equivalent exists for this, but I just
thought it would be neat if you could use foreach to do something like
this:

foreach (Object x in collection1, collection2)

and have it sequentially enumerate through both of them.

I think you can do something that comes quite close:

foreach (Object x in new Combine(collection1, collection2))

Where "Combine" is a class that stores the lists it gets in the ctor and
implements IEnumerable to enumerate over them.

Anyway, I think it would be nice to have real syntax support for this, as it
could remove unneccesary casting/boxing.

Niki
 
what happens if both of the collections are of different lengths though. and
where would you put the object from collection2 you can't put it into x
because that is where the item from collection1 is going and why stop at two
collection why not allow any number of collections. It might look like a
nice idea but it starts to get horribly complicated, however many
collections you allow in foreach some one is going to want 1 more
collection.

You could use a while loop and the collection iterators. Although there is
still the problem of what to do if the collections are of differnt lengths.

I'm not sure I can think of any reason why you would want to do this anyway.
Most of the things I can think of would be set type operations and you would
only want to iterate through one of the collection at a time anyway.

Paul.
 
Josh Ferguson said:
foreach (Object x in collection1, collection2)
and have it sequentially enumerate through both of them.

Sounds like a job for a nested loop, unless for some reason you really
need to do it very often.

foreach (Collection c in new Collection[] { collection1,
collection2 })
{
foreach (Object x in c)
{

P.
 
Back
Top