Search code examples
c#arraysmodel-view-controllerasp.net-mvc-viewmodel

What is the best practice to return a set of static data from 2 arrays


How do I return a set of data from two static arrays(String, Decimal) to a view? Example [Small, 1.00], [Medium, 3.00], [Large, 7.50].

I have been looking at Tuple<> which does return the data to the controller but I don't think it is the correct method as I would have to create new properties in my Viewmodel to then assign data to return to view.

class :

public class BoxSizeViewModel
{

    public static Tuple<string[], decimal[]> GetDetails()
    {
        string[] Size = { "S", "M", "L" };
        decimal[] Price = { 1, 3, 7.50 };

        return new Tuple<string[], decimal[]>(Size, Price);
    }
}

I Am trying to assign the size and price to IEnumerable that I can return to a view.


Solution

  • I think you would be better off using a new class or struct for holding the info you want to display. Still, if you want to use tuples, you should return a List of Tuples, instead of a Tuple of strings, like so:

    List<Tuple<string, decimal>>

    I still believe this will be more readable though:

    public class ProductInfo 
    {
       public string Size { get; set; }
       public decimal Price { get; set; }
    }
    
    public static List<ProductInfo> GetDetails()
    {
     ...
    }
    

    As for the matter of combining your lists, the Linq Zip operation is what you need.

    Check the code here: https://dotnetfiddle.net/qyryvY