Select first record from each group using Linq in ASP.Net

on Aug 13, 2020 04:15 AM

Get distinct value using linq

for example if we want to use var result = profits.distinct.Tolist()

it will give us these four records so it is correct. but what i want to achieve remove duplicate value ECONOCOM ANNTRES and get the the list as ECONOCOM ANNTRES  and PC THEFT

List<Profit> profits = new List<Profit>()
    new Profit("EC50AN", "ECONOCOM ANTRES"),
    new Profit("EC51AN", "ECONOCOM ANTRES"),
    new Profit("EPCTFT", "PC THEFT"),            
    new Profit("PCTFT", "PC THEFT")

i need to have also corresponding value also in the result

Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Aug 13, 2020 04:20 AM
on Aug 13, 2020 04:39 AM

Hi rakibxl,

In order to get distinct record you need to use GroupBy and Select method and select only first record from each group.



protected void Page_Load(object sender, EventArgs e)
    List<Profit> profits = new List<Profit>()
        new Profit(){Value="EC50AN", Text="ECONOCOM ANTRES" },
        new Profit(){Value="EC51AN", Text="ECONOCOM ANTRES" },
        new Profit(){Value="EPCTFT", Text="PC THEFT" },
        new Profit(){Value="PCTFT",  Text="PC THEFT" }
    var result = profits.GroupBy(x => x.Text).Select(x => x.First()).ToList();

public class Profit
    public string Text { get; set; }
    public string Value { get; set; }


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim profits As List(Of Profit) = New List(Of Profit)() From {
        New Profit() With {.Value = "EC50AN", .Text = "ECONOCOM ANTRES"},
        New Profit() With {.Value = "EC51AN", .Text = "ECONOCOM ANTRES"},
        New Profit() With {.Value = "EPCTFT", .Text = "PC THEFT"},
        New Profit() With {.Value = "PCTFT", .Text = "PC THEFT"}
    Dim result = profits.GroupBy(Function(x) x.Text).Select(Function(x) x.First()).ToList()
End Sub

Public Class Profit
    Public Property Text As String
    Public Property Value As String
End Class