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?
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();
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With