Distinct OrderBy in LINQ

One of my colleagues was curious to know how to implement a Distinct-OrderBy on a custom collection in LINQ. Here’s an example. This example uses the Distinct and OrderBy on the CustomerName property of the Customer class.


class Program
static void Main(string[] args)
var cust = (from c in Customer.GetCustomers()
select c.CustName)
.OrderBy(x => x);
foreach(var cst in cust)

class Customer
public int OrderId { get; set; }
public string CustName { get; set; }

public static List<Customer> GetCustomers()
List<Customer> cust = new List<Customer>();
cust.Add(new Customer() { OrderId = 1, CustName = "Zack" });
cust.Add(new Customer() { OrderId = 2, CustName = "Harry" });
cust.Add(new Customer() { OrderId = 3, CustName = "Jill" });
cust.Add(new Customer() { OrderId = 4, CustName = "Zack" });
cust.Add(new Customer() { OrderId = 5, CustName = "Martin" });
cust.Add(new Customer() { OrderId = 6, CustName = "Jill" });
return cust;


Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim cust = (
From c In Customer.GetCustomers()
Select c.CustName).Distinct().OrderBy(Function(x) x)
For Each cst In cust
Next cst
End Sub
End Class

Friend Class
Public Property OrderId() As Integer
Public Property
CustName() As String

Public Shared Function
GetCustomers() As List(Of Customer)
Dim cust As New List(Of Customer)()
cust.Add(New Customer() With {.OrderId = 1, .CustName = "Zack"})
cust.Add(New Customer() With {.OrderId = 2, .CustName = "Harry"})
cust.Add(New Customer() With {.OrderId = 3, .CustName = "Jill"})
cust.Add(New Customer() With {.OrderId = 4, .CustName = "Zack"})
cust.Add(New Customer() With {.OrderId = 5, .CustName = "Martin"})
cust.Add(New Customer() With {.OrderId = 6, .CustName = "Jill"})
Return cust
End Function
End Class

You can read more about Distinct and OrderBy


Distinct OrderBy LINQ

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

infopediaonline said...

this is an interesting tip