简体   繁体   中英

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.

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.

Your solution is okay but can be improved in two ways:

  1. Use a ternary operator ( ? : ) to turn the if-else statement into an expression.
  2. The as keyword tests whether an expression can be cast to the requested type and casts it if it can and returns null otherwise. This test is superfluous here, since you know in advance that A and B derive from Base . Use a simple cast instead.
IEnumerable<Base> foo = myObjects.Select(
    o => o.SomeProperty ? (Base)new A() : (Base)new B());

An alternative, is to specify the generic type parameters of the Select method explicitly; however, it requires you to specify both of them:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM