Jump to content
  • Advertisement
Sign in to follow this  
adt7

[C#] Mixed Collection Iteration

This topic is 3265 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say I have the following:
public interface IFoo
{
}

public interface IBar : IFoo
{
   void Bar();
}

public interface IUber : IFoo
{
   void Uber();
}


Is there a way of doing the following?
List<IFoo> list = new List<IFoo>();

void BarAll()
{
   foreach(IBar o in list)
      o.Bar();
}

void UberAll()
{
   foreach(IUber o in list)
      o.Uber();
}


Currently this works, but only for objects which are both IBar and IUber, I need it to work in cases where an object is only one of those. (Currently I can an unable to cast error) Is this even possible? Or something similar?

Share this post


Link to post
Share on other sites
Advertisement

List<IFoo> list = new List<IFoo>();

void BarAll()
{
foreach(IBar o in list.OfType<IBar>())
o.Bar();
}

void UberAll()
{
foreach(IUber o in list.OfType<IUber>())
o.Uber();
}



This works by using the LINQ extension .OfType(), which returns objects of that type and only of that type. This is similar to doing:


foreach (var o_tmp in list) {
IBar o = o_tmp as IBar;
if (o == null)
return;
}

Share this post


Link to post
Share on other sites
Fantastic, thanks for the quick answer. I didn't even know that method existed.

What are the performance considerations with it though? Am I better off sorting it into two lists instead?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!