【问题标题】:How to return a value from a foreach loop of a collection?如何从集合的 foreach 循环中返回一个值?
【发布时间】:2017-05-29 13:09:15
【问题描述】:

我有两个课程InvoiceInvoiceProductsInvoiceProducts 是一个集合,有一个名为 Price 的仅获取属性,我希望 Invoice 有一个名为 TotalPrice 的属性,它将返回添加到它的 InvoiceProducts 集合中的 Price foreach 项目。但是,我不确定是否要这样做。以我尝试使用的当前方式,我收到一条错误消息

“对象引用未设置为对象的实例。”有没有办法做到这一点?

目前的方式:

public class Invoice
{
    public int InvoiceID { get; set; }
    public string ClientName { get; set; }
    public DateTime Date { get; set; } = DateTime.Today;
    private decimal totalPrice;
    public decimal TotalPrice {
        get
        {
            return totalPrice;
        }
        set
        {
            foreach(var item in InvoiceProducts)
            {
                totalPrice += item.Price;
            }
        }
    }

    public virtual ICollection<InvoiceProducts> InvoiceProducts { get; set; }
}

public class InvoiceProducts
{
    public int InvoiceProductsID { get; set; }
    public int InvoiceID { get; set; }
    public int ProductID { get; set; }
    public int ProductQuantity { get; set; }
    public decimal Price { get { return Product.ProductPrice * ProductQuantity; } }

    public virtual Invoice Invoice { get; set; }
    public virtual Product Product { get; set; }
}

【问题讨论】:

  • 为 InvoiceProducts 添加初始化(例如 public virtual ICollection InvoiceProducts { get; set; } = new List();)
  • 你也可以删除TotalPrice的set部分,只使用get(当然是在return之前计算答案)

标签: c# entity-framework asp.net-mvc-5


【解决方案1】:
public decimal TotalPrice {
    get
    {
        return InvoiceProducts.Sum(product => product.Price);
    }
}

或更短,因为它只得到:

public decimal TotalPrice => InvoiceProducts.Sum(product => product.Price);

当然,您需要初始化您的产品列表,并且可能只获取它。

public Invoice() 
{
    InvoiceProducts = new List<InvoiceProcuct>();
}

public ICollection<InvoiceProduct> InvoiceProducts { get; }

【讨论】:

    【解决方案2】:

    我看到这个问题已经得到解答,但我想提供一些额外的说明,如果我可以尝试的话。 set 带有参数,并且是您在分配属性值时要运行的特殊逻辑,具体取决于您分配给它的内容。举个简单的例子:

      public class SpecialNumber
        {
            private double _theNumber; 
    
            public double TheNumber
            {
                get { return _theNumber; }
                set
                {
                    _theNumber = value * Math.PI;
                }
            }
        }
    

    保留字value 是表达式的右侧:

    specialNumberObject.TheNumber = 5.0;
    

    因此,setter 中的 value 将采用 5.0。如 S. Spindler 所示,您在 setter 中的逻辑非常适合 get,因为它定义了一个 自定义返回,您希望在我们想要 访问 时执行该返回 strong> 属性的值。

    我的班级的另一个版本可能决定有一个在输出时乘以 PI 的属性,如果我的班级中的后端逻辑依赖于其“未相乘形式”的数字,这可能会很有用。在这种情况下,逻辑更适合 getter。

    希望我没有混淆这个问题。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2014-12-19
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2016-04-24
      • 2011-01-25
      • 1970-01-01
      • 2016-01-30
      相关资源
      最近更新 更多