If there is a matching item at the beginning of the list, you will still add a duplicate.
You want to check whether index is zero as well.
Repeating items in the list
Question
Items that has the same item numbers should not repeat in the list, I tried this piece of code but it's not helping.
if (salesX.Count > 0)
{
foreach (SalesList saleX in salesX.ToList())
{
int index = sales.FindIndex(item => item.ItemNumber == saleX.ItemNumber);
if (index > 0)
{
sales[index].PosQuantity = +saleX.PosQuantity;
sales[index].PosSales = +saleX.PosSales;
}
else { sales.Add(saleX); }
}
}
Solution
OTHER TIPS
One possible solution would be to create a Dictionary list to define if the item exist.
The Dictionary would list all the unique ItemNumbers and you would use the ContainsKey method to determine if it already exists.
Change your condition to index != -1
, and it should work
if (index != -1)
{
sales[index].PosQuantity = +saleX.PosQuantity;
sales[index].PosSales = +saleX.PosSales;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow