I have a list of items
in the following format (Id, title, quantity, manufacturer)
Id | Title | Quantity | Manufacturer |
---|---|---|---|
1 | BluRay Player | 3 | Sony |
2 | CD Player | 2 | Sony |
3 | Fridge | 1 | LG |
4 | Washing Machine | 1 | Samsung |
I want to get return these items by Manufacturer and total quantity of items for that Manufacturer as below
Manufacturer Id | Manufacturer Name | Quantity |
---|---|---|
1234 | Sony | 5 |
1235 | LG | 1 |
1236 | Samsung | 1 |
I have a method doing the below
public void GetManufacturerData()
{
var manData = new HashSet<ManufacturerAndQuantity>();
foreach (var item in items)
{
var mq = new ManufacturerAndQuantity();
var manufac = myService.GetManufacturer(item.ManufacturerId);
mq.Title = manufac.Title;
mq.Id = manufac.Id;
mq.Total += item.Quantity;
if (!manData.Equals(c))
{
manData.Add(c);
}
}
}
The class (ManufacturerAndQuantity
) is
public class ManufacturerAndQuantity : IEquatable<ManufacturerAndQuantity>
{
public int? Id { get; set; }
public string Title { get; set; }
public int Total{ get; set; }
public bool Equals(ManufacturerAndQuantity? other)
{
return this.Id.Equals(other.Id);
}
}
The issue im facing is im using a HashSet which according to my research means it would only add unique items and would disregard any duplicate items so wont add them to the list.
At present it is still adding the same item even though i have a check against Id so if the same ID appears i dont want to add it (in this case there are two items of the Sony brand so it only should be adding the entry once but in addition i would like to update the quantity so i have an accurate count of the total manufacturer products).
Where am i going wrong?
I checked MSDN and other online links for HashSet usage which all have similar ways to add and declare but i may need a bit more guidance on this.
1