I am trying to use .distinct in Linq to get result based on one field of the table (so do not require a whole duplicated records from table).
I know writing basic query using distinct as followed:
var query = (from r in table1
orderby r.Text
select r).distinct();
but I need results where r.text
is not duplicated.
There are lots of discussions around this topic.
You can find one of them here:
One of the most popular suggestions have been the Distinct method taking a lambda expression as a parameter as @Servy has pointed out.
The chief architect of C#, Anders Hejlsberg has suggested the solution here. Also explaining why the framework design team decided not to add an overload of Distinct method which takes a lambda.
From what I have found, your query is mostly correct. Just change "select r" to "select r.Text" is all and that should solve the problem. This is how MSDN documented how it should work.
Ex:
var query = (from r in table1 orderby r.Text select r.Text).distinct();
data.Select(x=>x.Name).Distinct().Select(x => new SelectListItem { Text = x });
but I need results where r.text is not duplicated
Sounds as if you want this:
table1.GroupBy(x => x.Text)
.Where(g => g.Count() == 1)
.Select(g => g.First());
This will select rows where the Text
is unique.
try this code :
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
MoreLinq has a DistinctBy method that you can use:
It will allow you to do:
var results = table1.DistictBy(row => row.Text);
The implementation of the method (short of argument validation) is as follows:
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();
Daniel Hilgarth's answer above leads to a System.NotSupported
exception With Entity-Framework. With Entity-Framework, it has to be:
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
Source: Stackoverflow.com