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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With