//Items.cs
public class Items
{
public int ItemNumber { get; set; }
public DateTime ItemDate { get; set; }
public List<ItemsLine> ItemsLines { get; set; } = new List<ItemsLine>();
/// MergeItem appends the items from the sourceItem to the current item
/// </summary>
/// <param name="sourceItem">Item to merge from</param>
public void MergeItem( Items sourceItem)
{
//IEnumerable<ItemsLine> items = new List<ItemsLine>();
//IEnumerable<Items> items = ItemsLines.Union<item>
throw new NotImplementedException();
}
}
//ItemLine.cs
public class ItemsLine
{
public int ItemLineId { get; set; }
public int Quantity { get; set; }
public double Cost { get; set; }
// public double Total { get { return this.Cost * this.Quantity; } }
public ItemsLine(int itemLineId, int quantity, double cost)
{
this.ItemLineId = itemLineId;
this.Quantity = quantity;
this.Cost = cost;
}
public ItemsLine() { }
}
//Program.cs
private static void MergeItem()
{
var item1 = new Items();
item1.ItemsLines.Add(new ItemsLine()
{
ItemLineId = 1,
Cost = 10.33,
Quantity = 4,
});
var item2 = new Items();
item2.ItemsLines.Add(new ItemsLine()
{
ItemLineId = 2,
Cost = 5.22,
Quantity = 1,
});
item2.ItemsLines.Add(new ItemsLine()
{
ItemLineId = 3,
Cost = 6.27,
Quantity = 3,
});
item1.MergeItem(item2);
Console.WriteLine("Grand total after merge = {0}", item1.ItemsLines.Sum(i => i.Cost * i.Quantity));
}
The rules for merging items are:
- The
ItemsLine
instances in the.ItemsLines
of the Item passed intoMerge
, are added to thethis.ItemsLines
, or used to update existing items ItemsLine
has an ItemLineID that is unique in the list- If the incoming ItemsLine.ItmeLineID already exists in the list the Quantity of the incoming item should be added to the existing item and existing Cost should be adjusted to the average of the existing and the incoming costs
- If the incoming ItemsLine.ItemLineID doesn't exist in the list the ItemsLine should be added
I tried using below code but that didn't work
IEnumerable<ItemsLine> items = new List<ItemsLine>();
IEnumerable<Items> items = ItemsLines.Union<item>()
To merge do i need to use Concat?, so you can combine two collections that implement IEnumerable or the Linq join query to achieve mergeritem?