Return two types that derive from the same abstract class

I have an abstract class, let me call it Fruit.

There are two classes that come from Fruit, they will be called Apple and Pear.

I have a function that should return both apples and pears, for example, their expiration 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 to return two results?

Thank.

+4
source share
2 answers

You can do it:

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

It Unionwill work similarly instead Concat, but you probably don't need to worry about comparing the two types and breaking them off. I heard that it’s not good to compare apples with pears (oh wait, oranges).

Be sure to specify this namespace:

using System.Linq;

, , .OfType<Apple>(), .

+4

, - . var , = , Linq . , IEnnumarble.

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();
}
+5

Source: https://habr.com/ru/post/1666840/


All Articles