简体   繁体   中英

Adding and Changing Items in a array C#

I was wondering if you cloud help me?

I have an array that consist of items and prices and qty. If the item exist it the array it must update the price and the qty, If it doesn't exits it must be added

Here is my code that i have tried:

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

it is not working could you maby assist me on this?

Arrays in C# cannot have entries added to them after being initialised. You're better off using a List<String> instead, where you can add and remove entries from the list. Alternatively consider a Dictionary<Int32, String> , which would let you use the ItemCode as an identifier to make finding a given entry easier.

As a furthur point, instead of storing all your item data in a delimited string, make a new Class for them, with the various details as properties, and then you can use a theoretical Dictionary<Int32, ItemObject> for better clarity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM