【问题标题】:How do I get SingleOrDefault to return object by reference from a list?如何让 SingleOrDefault 从列表中通过引用返回对象?
【发布时间】:2011-08-03 19:16:28
【问题描述】:

考虑这些代码行:

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

我假设 SingleOrDefault 方法会通过引用返回对象,但事实并非如此。在更改了 ProdGroupItm 的 TOTAL_DOLLAR 金额后,ProdGroupItm2 保持不变,证明它们没有引用列表中的内容。为什么是这样?有没有办法更新列表中对象的值?

【问题讨论】:

  • ProductionCostCalcHelper 是一个结构吗?

标签: c# .net linq byref


【解决方案1】:

如果您的 ProductionCostCalcHelper 类型是可变的 struct,就会发生这种情况。
不要这样做; mutable structs are evil.

每次您传递struct 时,整个值都会复制到您要传递到的任何位置。

改用类。

【讨论】:

  • 谢谢,但它是一个类,而不是一个结构。
  • 那不应该发生。你在使用 LINQ to SQL 吗? itm.prodProdGroup是什么类型的?
  • 我刚刚找到了答案。 prodProdGroup 是一个 IEnumerable。我将其更改为 IList,它现在可以工作了。真是浪费了一天。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2012-02-13
  • 2012-06-23
  • 2019-05-23
  • 2019-03-19
  • 2020-10-06
  • 1970-01-01
  • 2013-01-25
  • 2015-01-04
相关资源
最近更新 更多