How to Get Distinct Values From a LINQ Query

Ever wondered how to get a distinct value set from a LINQ query?
Maybe you got that query from a database: var q = dataSet.Tables[0].AsEnumerable();
Or maybe it’s a query on a LINQ query: var q = from oq in originalQuery where oq.Active select oq.Id;

In SQL, you can simply use DISTINCT keyword to do that.
In LINQ, you simply use the Distinct() method:

var q = dataSet.Tables[0].AsEnumerable().Distinct();

Or, in the second case:

var originalQuery = from q in dataSet.Tables[1].AsEnumerable() select new { Id = q.Field<<nt>("Name"), Name = q.Field<string>("Name") };
var q = (from oq in originalQuery where oq.Active select oq.Id).Distinct();

It's fairly self-explanatory, but comment if you need an example 🙂

This entry was posted in Basics and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *