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?
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?
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#:
<!-- language: lang-cs -->public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.GroupBy(keySelector).Select(i => i.First());
}
####VB:
<!-- language: lang-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:
<!-- language: lang-cs -->var s = (from p in operatorList.DistinctBy(x => x.ID)
select p.ID, p.Name, p.Phone)