May 21, 2010

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.

C#

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

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;
}
}

VB.NET

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
Console.WriteLine(cst)
Next cst
Console.ReadLine()
End Sub
End Class

Friend Class
Customer
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

OUTPUT

Distinct OrderBy LINQ



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Distinct OrderBy in LINQ"
  1. infopediaonline said...
    May 21, 2010 6:04 PM

    this is an interesting tip

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions