Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to find duplicate element from my List in c#
following is my code

public List<Product> products_list = new List<Product>();
    static List<Product> cart_list = new List<Product>();

var product = products_list.Where(x=> x.prodID == Convert.ToInt32(product_id)); 
        
        foreach(var data in product){
            
            cart_list.Add(data);
          }


from above i didnt want duplicate element to add into cart

What I have tried:

i try this

var duplicates = list.GroupBy(s => s.ToUpper())
							 .Where(g => g.Count() > 1)
							 .Select(g => g.Key);
		
		foreach (var dupe in duplicates)
		{
			Console.WriteLine(dupe);
		}
Posted
Updated 8-Dec-19 20:34pm

public List<product> products_list = new List<product>();
static List<product> cart_list = new List<product>();

var product = products_list.Where(x=> x.prodID == Convert.ToInt32(product_id));

foreach(var data in product){
if(!cart_list.Exists(x=>x.prodID == data .prodID )){
cart_list.Add(data);
}
}
 
Share this answer
 
v3
Presumably, your list contains Product objects - because if it didn't then there would be no point in showing us the first code fragment - which means that your GroupBy relies on two things:
1) The Product class must override ToString - if it doesn't, then the comparison you use will compare the same value each time: "MyNamespace.Product" - and that will result in all items being in the same Group.
2) If Product overrides ToString, the returned string must differ significantly between different Products, but return identical strings for "duplicates".

At a guess, you want to compare some element of the Product - it';s PartNumber perhaps, maybe it's barcode - instead of a blanket string. But we have no access to your code, so we can't tell exactly what constitutes "duplicate" in terms of your code.
 
Share this answer
 
Rather than removing duplicates you should just not add them in the first place. As OriginalGriff has said, we don't know how you define "duplicate"

In this code I am assuming you don't want items with the same prodID

foreach (var data in product)
{
    if (!cart_list.Any(p => p.prodID == data.prodID))
    {
        cart_list.Add(data);
    }
}


Unrelated but don't use static for your cart. I know it looks like it is working but that 's because you only have one user....you. Browse your site from two different browsers and you'll see that all your users share a single cart. Use the Session to store the cart instead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900