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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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