Find Distinct Text Using LINQ

Another good use for LINQ popped up today in the forums. The person asked how to get distinct values from a series of text. I once again said LINQ! Here’s the sample text:

Apples, Oranges, Apples, Melons

We can use the Split method to turn this into an array. We can then use the Distinct method to only return the distinct values. Here’s the code:

C#

var unique = "Apples, Oranges, Apples, Melons"
.Split(new string[] { ", " },
StringSplitOptions.RemoveEmptyEntries).Distinct();
foreach (var item in unique)
{
Response.Write(item + "<br />");
}

VB.NET

Dim unique = "Apples, Oranges, Apples, Melons" _
.Split(New String(){", "},StringSplitOptions.RemoveEmptyEntries).Distinct()
For Each item In unique
Response.Write(item & "<br />")
Next item

The result is below:

image



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


About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

No comments: