Akhil
Akhil

Reputation: 2030

Avoid Duplicate in LINQ

I have a scenario like below. Actually i got the expected result. But need to avoid duplicate in one field.

I have a custom class to display records in my report. The class like below:

public class MyData
{
    public int ID;

    public string InvoiceNumber;

    public string DeliveryNoteNumber;

    public string QuotationNumber;
}

Here the flow is 1. Quotation Details 2. Delivery Details. Single Delivery Note can be multiple Quotations 3. Invoice Details. Here single invoice can have multiple Delivery Notes.

So when my invoice report i need to display all Delivery Notes of that Invoice need to display in a label with comma separated. Like all Quotations needs to be displayed with comma separated.

Here i have one problem. I have multiple quotations in one delivery note and add that delivery note to one invoice. So in reports i can show quotations with comma separated but delivery notes also duplicated. I used Group Join to group the data and the code and example is following

List<MyData> data = new List<MyData>();

MyData d1 = new MyData();
d1.ID = 1;
d1.InvoiceNumber = "Inv001";
d1.DeliveryNoteNumber = "DN001";
d1.QuotationNumber = "Q001";
data.Add(d1);

MyData d2 = new MyData();
d2.ID = 1;
d2.InvoiceNumber = "Inv001";
d2.DeliveryNoteNumber = "DN001";
d2.QuotationNumber = "Q002";
data.Add(d2);

var source = data.GroupBy(i => new { i.ID, i.InvoiceNumber })
       .Select(g => new MyData
       {
           ID = g.First().ID,
           InvoiceNumber = g.Key.InvoiceNumber,
           DeliveryNoteNumber = string.Join(", ", g.Select(i => i.DeliveryNoteNumber)),
           QuotationNumber = string.Join(", ", g.Select(i => i.QuotationNumber)),
       });

label1.Text = source.FirstOrDefault().DeliveryNoteNumber;
label2.Text = source.FirstOrDefault().QuotationNumber;

The output in the text boxes are below:

Text1Result  = DN001, DN001
Text2Result  = Q001, Q002

Here first Text box is the problem. Please give idea to solve this issue. Or I need to change Stored Procedure to accommodate this. My Custom class (MyData) is populated from sp (here I just hard coded for example). The sp created using join with Quotation table, Delivery Note Table and Invoice Table

Upvotes: 2

Views: 1984

Answers (1)

Michael Dunlap
Michael Dunlap

Reputation: 4310

You can avoid duplicates using Distinct() in LINQ.

var source = data.GroupBy(i => new { i.ID, i.InvoiceNumber })
           .Select(g => new MyData
           {
               ID = g.First().ID,
               InvoiceNumber = g.Key.InvoiceNumber,
               DeliveryNoteNumber = string.Join(", ", g.Select(i => i.DeliveryNoteNumber).Distinct()),
               QuotationNumber = string.Join(", ", g.Select(i => i.QuotationNumber).Distinct()),
           });

Upvotes: 2

Related Questions