Reputation: 965
Ok, maybe I'm just blind, but answer is eluding me:
so, model:
public class Dimensions
{
public int Width { get; set; }
public int Height { get; set; }
public int TypeId { get; set; }
public int PeacesForItem { get; set; }
}
and I have a method that is filtering the List:
public List<Dimensions> Consolidation(List<Dimensions> vm)
{
var list = new List<Dimensions>();
if (vm != null)
{
var typeIds = vm.Select(x => x.TypeId).ToHashSet();
foreach (var t in typeIds)
{
foreach(var item in vm)
{
if (t == item.IvericaId)
{
int x = 0;
foreach (var again in vm)
{
if (item.Duzina == again.Duzina && item.Sirina == again.Sirina && item.TypeId== again.TypeId)
{
x ++;
// vm.Remove(item); Not working, who would figure
}
}
list.Add(
new Dimensions
{
Width = item.Width,
Height = item.Height,
TypeId= item.TypeId,
PeacesForItem = x * item.PeacesForItem,
}
);
}
}
}
}
return list;
}
This method is iterating thru List items and checks if there are elements of same dimensions. If there are, then it is doubling needed quantity.
QUESTION: This code is still adding duplicates to new list, and I need to filter that out.
I tried numerous approaches, but every one I came up with has some fatal flaw in the design.
Upvotes: 1
Views: 141
Reputation: 35730
public List<Dimensions> Consolidation(List<Dimensions> vm)
{
return vm.GroupBy(d=>new {d.TypeId, d.Width, d.Height}) // if there are any duplicates, they are grouped here
.Select(g=>new Dimensions(){TypeId = g.Key.TypeId ,
Width = g.Key.Width,
Height = g.Key.Height,
PeacesForItem = g.Sum(dim=>dim.PeacesForItem)}) // number of duplicates in group calculated
.ToList();
}
Upvotes: 5
Reputation: 56459
You've massively over-complicated this one :). You don't need the nested loop, plus you're not doubling the value, you're squaring it? Try this:
var list = new List<Dimensions>();
if (vm != null)
{
foreach (var item in vm)
{
//Not sure how you identify dupes, may need to change the filter here
var duplicate = vm
.Where(v => v.PeacesForItem == item.PeacesForItem);
if (dupes.Any())
{
list.Add(new Dimension
{
Width = item.Width,
Height = item.Height,
TypeId = item.TypeId,
PeacesForItem = item.PeacesForItem * 2;
});
}
}
}
return list;
Upvotes: 2
Reputation: 76
dublicate the vm-List and iterate over the duplicated list and delete the object form the original list
public List<Dimensions> Consolidation(List<Dimensions> vm)
{
var list = new List<Dimensions>();
if (vm != null)
{
var dublicate = new List<Dimensions>(vm);
var typeIds = vm.Select(x => x.TypeId).ToHashSet();
foreach (var t in typeIds)
{
foreach(var item in dublicate )
{
if (t == item.IvericaId)
{
int x = 0;
foreach (var again in dublicate )
{
if (item.Duzina == again.Duzina && item.Sirina == again.Sirina && item.TypeId== again.TypeId)
{
x ++;
vm.Remove(item); //Now working
}
}
list.Add(
new Dimensions
{
Width = item.Width,
Height = item.Height,
TypeId= item.TypeId,
PeacesForItem = x * item.PeacesForItem,
}
);
}
}
}
}
return list;
}
Upvotes: 0