I have a column in a dataview with double type. I have to check if all the values in the column are different from each other.
Is there a way to do it through linq ?
I have a column in a dataview with double type. I have to check if all the values in the column are different from each other.
Is there a way to do it through linq ?
If you want to compare floating point types I would really advise to define your own IEqualityComparer<T>
where you overwrite the Equals()
method in order to specify the measure of the equality, because floating point numbers are not that easily comparable.
If your compared values comes from some calculations then it is only one more reason to compare them properly or it could happen that number 2 which you see will not match another number 2 just because it is 2.000000001 or so.
Therefore, use the following LINQ query
double[] items = new[] { 1d, 2d, 3d };
var dups = items.GroupBy(i => i, new MyDoubleComparer())
.Where(g => g.Count() > 1)
.Select(g => g.Key);
with your own comparer. You can specify how much precise it should be.
class MyDoubleComparer : IEqualityComparer<double>
{
public bool Equals(double x, double y)
{
// your comparing logic here
}
public int GetHashCode(double obj)
{
throw new NotImplementedException();
}
}
For inspiration how to compare floating points, navigate here or here.
listOfItems.Distinct().Count() == listOfItems.Count
Assuming listOfItems is a List<double>
You can try to find duplicates:
int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };
var duplicates = listOfItems
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
If duplicates contains values all the values in your column are not different from each other.
var distinctValues = view.ToTable(true, "YourColumn");
if(distinctValues.Rows.Count == view.Count)
//Column values are same