linq query to display data

djnilo dj 6 Reputation points
2022-12-15T17:52:35.467+00:00

hello good afternoon programmers I have an order application made visual studio 2015 entity c# linq
I am in the printing part, make a query to show the data, this query is wrong

an order containing

product name quantity
french fries girls 1
chicken boy 1
french fries girls 1

when making the query it brings me

report = printlist.GroupBy(x => x.ProductId).Select(group => group.First()).ToList();

I get this output is wrong

product name quantity
french fries girls 1
chicken boy 1

public static void PrintReceipt(BOX box, List

Computer Vision
Computer Vision
An Azure artificial intelligence service that analyzes content in images and video.
415 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2022-12-15T18:52:09.713+00:00

    The GroupBy groups all rows together that have the same key. In your case you're grouping by ProductId therefore all entities that have the same ProductId are grouped together. From this group you are then grabbing just the first product from that group so you're basically just getting the unique rows. If you want to group the products together and show the correct quantity then you need to count the items.

       var report = printlist.GroupBy(x => x.ProductId)   //Group items by product id  
                   .Select(group => new Vi_Sales_Detail () {          //For each group return back the product and the total # of items that match it  
                                  ProductId = group.Key,   //The product that the group matches  
                                  Quantity = group.Count()  //The # of items that are in group  
                               })  
                   .ToList();   //Make a list out of it  
    

    Of course your Vi_Sales_Detail needs to have get/set properties that line up with the query I gave. Adjust accordingly.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.