Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Distinct on specific field

Given:

var s = (from p in operatorList                       
    select p.ID, p.Name,p.Phone)

How would I return the Distinct records based only on the ID?

like image 273
John S Avatar asked May 12 '11 21:05

John S


People also ask

How to Select Distinct values in LINQ?

It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL). IEnumerable<data type> result = numbers. Distinct();

What is LINQ in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.


1 Answers

If you wanted to add the ability to do this as an extension method, here's a method called DistinctBy which takes in the source and keySelector as parameters and returns the distinct item set. It does the same thing as Ahmad's second query, but looks a little prettier inline.

C#:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
                                this IEnumerable<TSource> source, 
                                Func<TSource, TKey> keySelector)
{
    return source.GroupBy(keySelector).Select(i => i.First());
}
VB:
<Extension()>
Public Function DistinctBy(Of TSource, TKey)(
                    ByVal source As IEnumerable(Of TSource),
                    ByVal keySelector As Func(Of TSource, TKey))
                    As IEnumerable(Of TSource)

    Return source.GroupBy(keySelector).Select(Function(i) i.First())
End Function

Then call like this:

var s = (from p in operatorList.DistinctBy(x => x.ID)                       
         select p.ID, p.Name, p.Phone)
like image 141
KyleMit Avatar answered Jan 04 '23 08:01

KyleMit