Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling list with different types of objects

Tags:

c#

wrapper

I'm working on a recommendation algorithm which all works fine. But now I wanted to implement this code into the branch of my development team.

I'll start from the top. My algorithm can recommend 2 types of objects, restaurants and dishes.

Restaurant:

public class Restaurant
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
    public List<Tag> Tags { get; set; } = new List<Tag>();
    public int PriceRange { get; set; }
}

And dish:

public class Dish
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
    public virtual Restaurant rest { get; set; }
    [ForeignKey("rest")]
    public Guid RestaurantId { get; set; }
    public List<Tag> Tags { get; set; }
}

Now my product owner wants the list to be like this when it's being presented on the home page of our app:

[Restaurant][Dish][Restaurant][Dish] Etc...

So basically, he wants to alternate the type of object that's being recommended. These dishes and restaurants are completely separate. They are generated by my algorithm purely on the user's preferences and have no correlation with eachother at all.

Now my problem is how to return such a list. I figured I'd need a wrapper class which contains either a Restaurant or Dish like this:

public class RecommenderItem
{
    public Restaurant rest { get; set; }
    public Dish dish { get; set; }
}

This way I can create a List<RecommenderItem> and return that to the client. The client would only need to check which attribute is null and retrieve the values from the one that is not.

I'm just unsure if this is the correct approach. Are there any 'best practices' in doing this? Let me know if I should elaborate more!


2 Answers

If they doesn't have common base class then creating one wrapper class is the best solution. At the same time you can be more flexible and create something like

public class RecommendationItem
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string PageUrl { get; set; }
    public object Entity { get; set; }
}

So you can include all common information in this class and client will not be required to check with which object type he works. In such case it would be easier to add one more item type. At the same type I added reference to entity itself - it can be used if some specific handling for one or two item types is required.

like image 125
oryol Avatar answered Dec 06 '25 06:12

oryol


You can declare an interface IRecommenderItem:

public interface IRecommenderItem
{
    //shared properties
}

public class Restaurant : IRecommenderItem
{

}

public class Dish : IRecommenderItem
{

}

than, you can type:

List<IRecommenderItem> m = new List<IRecommenderItem>();
like image 36
elviuz Avatar answered Dec 06 '25 05:12

elviuz