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

Time:12-07

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.

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.

CodePudding user response:

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.

CodePudding user response:

An alternative is to specify the the generic type parameters of Select explicitly:

IEnumerable<Base> foo = myObjects.Select<SourceDataType, Base>(o =>
    o.SomeProperty ? new A() : new B());

Also, using the ternary operator ? : simplifies the lambda.

  • Related