I have a program that allows the user to buy items and it places each item in a List. This is the shopping basket. I want the program to also display their receipt. However if the user buys a lot of items then just listing out their basket will make the receipt too long. So I tried to display the duplicate items in the list:
static void generateReceipt(List<string> basket)
{
for (int i = 0; i < basket.Count(); i++)
{
Console.WriteLine(basket.Count(x => x == basket[i]) + "x ................ " + basket[i]);
}
}
However when I run this with, let's say 5 duplicate 'cake' in the basket the output will look like:
5x ............. cake
5x ............. cake
5x ............. cake
5x ............. cake
5x ............. cake
How would I get my function to just display a single "5x .......... cake"? What am I missing?
You can use Distinct()
static void generateReceipt(List<string> basket)
{
foreach(var item in basket.Distinct())
{
Console.WriteLine(basket.Count(x => x == item) + "x ................ " + item);
}
}