【问题标题】:Adding and Changing Items in a array C#在数组 C# 中添加和更改项目
【发布时间】:2014-10-05 07:51:22
【问题描述】:

我想知道你是否云帮助我?

我有一个由商品、价格和数量组成的数组。 如果项目存在,则必须更新价格和数量的数组,如果不存在则必须添加

这是我尝试过的代码:

if (line.Contains(ItemCode))
{
    string[] details = line.Split(new string[] { "|" }, StringSplitOptions.None);
    {
        for (int i = 0; i < details.Length; i++)
        {
            if (details[i].Contains(ItemCode))
            {
                string[] line_details = details[i].Split(',');
                string replace = line_details[2].Trim() + "," + line_details[3].Trim();
                double NewQty = double.Parse(Qty) + double.Parse(line_details[2]);
                double NewPrice = (double.Parse(UnitPrice) * double.Parse(Qty));
                double NewUnitPrice = NewPrice + double.Parse(line_details[3]);
                string new_replace = NewQty + "," + NewUnitPrice;
                line = line.Replace(replace, new_replace);
            }
        }
    }
}
else
{  
    line = line + "\"Detail\",0," + Qty + "," + (double.Parse(UnitPrice) * double.Parse(Qty)) + "," + InclusivePrice + ",\"" + UnitUsed + "\"," + TaxType + "," + DiscountType + "," + DiscountPercentage + ",\"" + ItemCode + "\",\"" + Description + "\"," + SearchType + "," + "\"\"" + ",\"" + MultiStore + "\"|" + Environment.NewLine;
}

它不工作你能帮我解决这个问题吗?

【问题讨论】:

  • string[] details = line.Split...;代替List&lt;string&gt; details = new List&lt;string&gt;(line.Split(new string[] { "|" }, StringSplitOptions.None));

标签: c# arrays replace


【解决方案1】:

C# 中的数组在初始化后不能添加条目。您最好使用List&lt;String&gt;,您可以在其中添加和删除列表中的条目。或者考虑使用Dictionary&lt;Int32, String&gt;,它可以让您使用ItemCode 作为标识符,以便更轻松地查找给定条目。

另外一点,不要将所有项目数据存储在分隔字符串中,而是为它们创建一个新类,将各种详细信息作为属性,然后您可以使用理论上的Dictionary&lt;Int32, ItemObject&gt; 以获得更好的清晰度。

【讨论】:

  • 谢谢你的回答,它对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 2011-04-21
  • 2014-03-21
  • 2013-09-05
相关资源
最近更新 更多