开发者

How do I get SingleOrDefault to return object by reference from a list?

开发者 https://www.devze.com 2023-03-24 20:39 出处:网络
Consider these lines of code: //prodProdGroup is a list within the itm object that I need to search. The items

Consider these lines of code:

  //prodProdGroup is a list within the itm object that I need to search. The items
  //within the list are of type ProductionCostCalcHelper. I need to find one
  //of the ProductionCostCalcHelper records in the list, calculate its total dollar value
  //and assign it the value

  ProductionCostCalcHelper prodGroupItm = itm.prodProdGroup.SingleOrDefault(f => f.MAST_PROJ.Trim() == laborItm.MAST_PROJ.Trim());
  ProductionCostCalcHelper prodGroupItm2 = itm.prodProdGroup.SingleOrDefault(f => f.MAST_PROJ.Trim() == laborItm.MAST_PROJ.Trim());

  if (prodGroupItm != null)
  {
        prodGroupItm.TOTAL_DOLLAR = avgDollarsPerHour * prodGroupItm.HOURS;
  }

I'm assuming that the SingleOrDefault method would return the object by reference but it doesn't. After changing the TOTAL_DOLLAR amount of ProdGroupItm, ProdGroupItm2 remains the same proving that they are not referen开发者_开发技巧cing what is in the list. Why is this? Is there a way to update the value of the object within the list?


This would happen if your ProductionCostCalcHelper type is a mutable struct.
Don't do that; mutable structs are evil.

Every time you pass a struct around, the entire value is copied to whatever you're passing it to.

Use a class instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号