How to show Distinct data using Linq to SQL

By bryan tugade

We can show Distinct data in gridview using Linq to SQL. We can compare in the result how the distinct function works in Linq to sql. Here's how.

Imports Microsoft.VisualBasic
Imports System.Linq
Imports System.Data.Linq

Partial Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        Dim adventureContext = New adventureWorks()

            Dim original_employee = (From employee In adventureContext.Employees Select employee.Title)

             Dim distinct_employee = (From employee In adventureContext.Employees Select employee.Title).Distinct()

             GridView1.DataSource = distinct_employee
            GridView2.DataSource = original_employee
        Catch ex As Exception


        End Try
    End Sub
End Class

And here's the compared result of two queries.

As you can see the original data are not sorted and repeatedly shown in the gridview unlike when you used the distinct in Linq to sql the data are sorted and the data shown distinctively.

That's it! Happy Coding. : )

Related FAQs

In C#, we can select and deselect checkbox in gridview in onPostback event of checkbox in gridview header.
We can select multiple fields in a given database tables using Linq to sql. I use AdventureWorks as my database in this sample app and to show you how it works i bind the results in gridview control.
We can hover on gridview row using javascript onmouseover event. We can also change the color in code behind.
We can filter data using dataview.
This snippet shows how to connect to SQLExpress and execute stored procedure.
Assuming that you need to create an application that needs to transfer data from sql server to microsoft excel. The first thing you need to do is to find a way to connect to sql server. We can do this by using visual basic application.
How to show Distinct data using Linq to SQL  (1931 Views)