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






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