【问题标题】:What is the best practice to return a set of static data from 2 arrays从 2 个数组返回一组静态数据的最佳做法是什么
【发布时间】:2019-11-02 15:43:20
【问题描述】:

如何将一组数据从两个静态数组(字符串、十进制)返回到视图?示例 [小,1.00]、[中,3.00]、[大,7.50]。

我一直在查看 Tuple 确实将数据返回到控制器,但我认为这不是正确的方法,因为我必须在我的 Viewmodel 中创建新属性然后分配数据以返回到视图。

类:

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);
    }
}

我正在尝试将大小和价格分配给 IEnumerable,以便我可以返回视图。

【问题讨论】:

  • 你可以返回带有 size 和 price 属性的类
  • 如果这些尺寸与价格相匹配,为什么不使用Tuple&lt;string, decimal&gt;[],或者更好的是使用值元组(string Size, decimal Price)[] 或创建一个包含尺寸和价格值的类。

标签: c# arrays model-view-controller asp.net-mvc-viewmodel


【解决方案1】:

我认为你最好使用一个新的类或结构来保存你想要显示的信息。不过,如果你想使用元组,你应该返回一个元组列表,而不是一个字符串元组,如下所示:

List&lt;Tuple&lt;string, decimal&gt;&gt;

我仍然相信这将更具可读性:

public class ProductInfo 
{
   public string Size { get; set; }
   public decimal Price { get; set; }
}

public static List<ProductInfo> GetDetails()
{
 ...
}

至于合并列表的问题,Linq Zip 操作就是你所需要的。

在此处查看代码:https://dotnetfiddle.net/qyryvY

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多