Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return two types that derive from the same abstract class

Tags:

c#

linq

I have an abstract class, let's call it Fruit.

There are two classes that derive from Fruit, let's call them Apple and Pear.

I have a function that needs to return both apples and pears by, let's say, their expiry date.

It looks something like this:

public Fruit[] GetFruitByDate(string date){
Apple[] apples=/*Linq result*/;
Pear[] pears=/*Linq result*/;
return apples+pears;//what do I do here?
}

How do I return the two results?

Thanks.

like image 520
master2080 Avatar asked Jan 05 '23 17:01

master2080


2 Answers

If you have to keep casting things you're doing something wrong, or don't have a clear understanding of inheritance. putting a question with var and no real code after the = doesn't allow for a proper answer since Linq can return different types. I'll just assuming it returns and IEnnumarble of some sort.

public Fruit[] GetFruitByDate(string date){
List<Fruit> tResult = new List<Fruit>();
var apples=/*Linq result*/;
var pears=/*Linq result*/;
tResult.AddRange(apples);
tResult.AddRange(pears);
return tResult.ToArray();
}
like image 168
Peter4499 Avatar answered Jan 07 '23 06:01

Peter4499


You could do this:

return apples.Cast<Fruit>().Concat(pears).ToArray();

Equally Union would work instead of Concat, but you probably don't need to worry about comparing the two types and de-duping them. I hear it's not good to compare apples to pears (oh wait, that's oranges).

Be sure to include this namespace:

using System.Linq;

When you call this method, if you need to get back to the subclass members, then you will need to do a safe cast on each item, or separate the types back out with by calling .OfType<Apple>() for example.

like image 27
Stuart Avatar answered Jan 07 '23 07:01

Stuart