Distinct not working with LINQ to Objects
LINQ Distinct is not that smart when it comes to custom objects.
All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields).
One workaround is to implement the IEquatable interface as shown here.
If you modify your Author class like so it should work.
public class Author : IEquatable<Author>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Equals(Author other)
{
if (FirstName == other.FirstName && LastName == other.LastName)
return true;
return false;
}
public override int GetHashCode()
{
int hashFirstName = FirstName == null ? 0 : FirstName.GetHashCode();
int hashLastName = LastName == null ? 0 : LastName.GetHashCode();
return hashFirstName ^ hashLastName;
}
}
Try it as DotNetFiddle
Not getting Distinct Items when using Linq to List?
Use
var queryResults = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault())
PatientList = queryResults.ToList<SelectListItem>();
You can always try
PatientList = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault()).ToList<SelectListItem>();
It will give you the distinct results based off whatever you group by
Check out http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx
Also another question for reference: Returning a Distinct IQueryable with LINQ?
Distinct not working with LINQ to Objects
LINQ Distinct is not that smart when it comes to custom objects.
All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields).
One workaround is to implement the IEquatable interface as shown here.
If you modify your Author class like so it should work.
public class Author : IEquatable<Author>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Equals(Author other)
{
if (FirstName == other.FirstName && LastName == other.LastName)
return true;
return false;
}
public override int GetHashCode()
{
int hashFirstName = FirstName == null ? 0 : FirstName.GetHashCode();
int hashLastName = LastName == null ? 0 : LastName.GetHashCode();
return hashFirstName ^ hashLastName;
}
}
Try it as DotNetFiddle
ASP.net Core C# Linq Distinct not working
Your class ProcessListSummary
probably does not override Equals
and GetHashCode
, so the default will be used from System.Object
that just compares references. You use always a new instance of ProcessListSummary
, so all are considered to be unequal.
So either override Equals
+GetHashCode
meaningfully, by comparing the relevant properties, and/or implement IEquatable<ProcessListSummary>
(in the same way) or pass a custom IEqualityComparer<ProcessListSummary>
to Distinct
. The latter should be done if you have multiple ways to compare this class or you don't want to change (or can't change) it in general.
Another option is to use Distinct
on an anonymous type or tuple which provide that feature:
PLDistinct = PL
.Select(p => (p.Title,p.WSID,p.QImageTnURL,p.QImageURL,p.QDescription,p.PComplete,p.MIdent,p.WID))
.Distinct()
.Select(p => new ProcessListSummary { Title= p.Title,
WSID = p.WSID,
QImageTnURL = p.QImageTnURL,
QImageURL = p.QImageURL,
QDescription = p.QDescription,
PComplete= p.PComplete,
MIdent = p.MIdent,
WID = p.WID})
.ToList();
Using Distinct with LINQ and Objects
I believe this post explains your problem:
http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx
The content of the above link can be summed up by saying that the Distinct() method can be replaced by doing the following.
var distinctItems = items
.GroupBy(x => x.PropertyToCompare)
.Select(x => x.First());
Distinct() on anonymous object not working in LINQ
You are using DateTime.Now
for Created/Updated, so it would be quite unlikely that values between entries would be the same, they most likely differ by fraction of millisecond. If you displayed the values with greater precision, eg. .Ticks
, they would be different.
I think you should save DateTime.Now
to variable before LINQ and use it, to ensure they are the same for all entries. Other option is to add it to the object after .Distinct()
.
LINQ Distinct Not Working
You need to tell the Distinct
method what equality comparer to use. I would also split that out into it's own class. For example:
Public Class TesteEqualityComparer
Implements IEqualityComparer(Of Teste)
Public Function Equals2(x As Teste, y As Teste) As Boolean Implements IEqualityComparer(Of Teste).Equals
Return x.Codigo = y.Codigo
End Function
Public Function GetHashCode1(obj As Teste) As Integer Implements IEqualityComparer(Of Teste).GetHashCode
Return obj.Codigo.GetHashCode()
End Function
End Class
And now your query is:
MsgBox(l.Distinct(New TesteEqualityComparer()).Count())
Linq Distinct not bringing back the correct results
So, you want to group them by Serial Number and retrieve the full DataRow? Assuming that after grouping them we want to retrieve the first item:
var distinctList = dt.AsEnumerable().GroupBy(a => a.Field<string>("SERIAL NUMBER"))
.Select(a => a.FirstOrDefault()).Distinct().ToList();
EDIT: As requested
var distinctValues = dt.AsEnumerable().Select(a => a.Field<string>("SERIAL NUMBER")).Distinct().ToList();
var duplicateValues = dt.AsEnumerable().GroupBy(a => a.Field<string>("SERIAL NUMBER")).SelectMany(a => a.Skip(1)).Distinct().ToList();
var duplicatesRemoved = dt.AsEnumerable().Except(duplicateValues);
Linq Distinct() is not working
use GroupBy
instead of Distinct
Related Topics
Comparing Two Byte Arrays in .Net
How to Convert Byte Array to String
How to Easily Convert Datareader to List≪T≫
How to Get Httpcontext.Current in ASP.NET Core
How to Monitor SQL Server Table Changes by Using C#
Best Way to Compare Two Complex Objects
Show Console in Windows Application
How to Enable C# 6.0 Feature in Visual Studio 2013
How to Modify a CSS Style in the Code Behind File for Divs in ASP.NET
Build and Load Assetbundles in Unity
How to Migrate a .Net Windows Service Application to Linux Using Mono
How to Compile .Net Core App for Linux on a Windows MAChine
How to Compile a Windows.Forms Application on Linux for .Net Core
What Are Automatic Properties in C# and What Is Their Purpose
How to Loop Through All Enum Values in C#
Is Datetime.Now the Best Way to Measure a Function'S Performance
Why Doesn't C# Allow Static Methods to Implement an Interface