Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning different sub-types in a linq .Select() statement

Let’s say I have two classes in C# that derive from the same base class:

class Base {}

class A: Base {}

class B: Base {}

I’m working with a list of objects that I want to project to different sub-types of type Base. So I did something like this:

IEnumerable<Base> foo = myObjects.Select(o => {
  if(o.SomeProperty){
    return new A();
  } else {
    return new B();
  }
});

however, this does not compile, the compiler throws an error saying it can’t infer the return type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question is: what is the most elegant way to specify the return type in cases like this? At the moment I’ve changed the lambda body to this:

if(o.SomeProperty){
  return new A() as Base;
} else {
  return new B() as Base;
}

this works, but I’m wondering if there is a better way.

>Solution :

Your solution is good, you can also explicitly point types in Select extension method like this:

IEnumerable<Base> foo = myObjects.Select<T, Base>(o => {
  if(o.SomeProperty)
  {
    return new A();
  } 
  else 
  {
    return new B();
  }
});

T is a type of your myObjects collection here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading