在 .NET Winfroms C# 应用程序中,我有一个名为 listItems 的 Dictionary 集合。我在应用程序启动时将数据存储在其中。在静态类中,我有以下内容:
// listItems is populated bt reading a file.
// No other operations are performed on it, except finding an item.
public static Dictionary<string, RefItemDetails> itemsList;
// Find RefItemDetails of barcode
public static RefItemDetails FindRefItem(string barcode)
{
RefItemDetails itemDet = null;
try
{
//if (itemsList.TryGetValue(barcode, out itemDet) == false)
// System.Diagnostics.Debug.WriteLine("Barcode " + barcode + " not found in Items");
//itemDet = itemsList.First(item => item.Key == barcode);//.First(item => item.Barcode == barcode);
if (itemsList.ContainsKey(barcode) )
itemDet = itemsList[barcode];
}
catch (Exception)
{
itemDet = null;
}
return itemDet;
}
为了从另一个类的 listItems 中检索项目,我使用:
refScannedItem = null;
// Get Unit Barcode & Search RefItem of it
refScannedItem = UtilityLibrary.FindRefItem(boxItem.UnitBarcode.Trim());
// Display BOX item details
refScannedItem.Barcode = boxItem.BoxBarcode.Trim();
refScannedItem.Description = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
refScannedItem.Retail *= boxItem.Quantity;
refScannedItem.CurrentCost *= boxItem.Quantity;
上面发生的情况是,我搜索一个项目并得到它“ refScannedItem
”,然后我将它的描述附加到"BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
. 因此,如果原始描述是“Aquafina”,我将其设为“BOXof 10 Aquafina”。嵌套时间我扫描相同的产品,我找到了产品,但现在它的描述变成了“10 盒 Aquafina”,所以我的设置描述线变成了“10 盒 10 盒 Aquafina”。类似“10 盒 10 盒 10 盒 Aquafina”等等。
正如您在我的查找代码中看到的那样,我最初使用TryGetValue
,然后尝试使用LINQ
,然后尝试使用ContainsKey
,但在所有这些中,为什么 listItem 的值会被更新。
我知道 asTryGetValue
有out
参数,所以值作为 a 传递reference
,然后它将被更改。但listItems[key]
也在更新它!我怎样才能避免这种情况发生?我选择了Dictionary
集合以便于快速搜索,但这部分在我的应用程序上也带来了很多问题和一个大错误。我找不到接收值但不应该更新的解决方案。所有文章都显示了如何搜索和更新它。
请为上述问题提出解决方案。非常感谢任何帮助。
谢谢