views:

87

answers:

3

Hi Everyone,

Hi have an issue with Linq. I have an array of double values with duplicate entries. I want to extract only distinct values from it. I have the following code which doesn't work correctly.

double[] dIds = GetIds(); //dIds has more than 10,000 items

var itemIdCollection = from id in dIds.Distinct()
                   select id;

Console.WriteLine(itemIdCollection.count().ToString());  //count is just 2 !!!!

Can you please give me a solution on this?

Thank you,

A: 

Try this:

List<double> x = new List<double>()
{
    3, 4, 5, 6, 7, 7, 7, 8, 8
};

List<double> distinct = x.Distinct().ToList();

distinct.ForEach(y => Console.WriteLine(y));
Console.ReadKey();
Tejs
ForEach extension doesn't belong to .Net standard libraries...you should provide it (even if very simple to find or implement)
digEmAll
ForEach is an extension on Lists provided with Linq as part of .NET.
Tejs
@digEmAll - http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx
John Rasch
Sorry, I dislike it so much that I've forgotten its esistence. :P
digEmAll
ForEach is not an extension on lists and is not a part of LINQ. It's a perfectly ordinary method on the list type.
Eric Lippert
Yup, you're right! That's my mistake, everything that looks like a Linq query I tend to call a Linq method without knowing better =D
Tejs
+1  A: 

First off, you don't have to do that freaky select. Just call dIds.Distinct(). Second, I can guarantee you that it works on any array of doubles. Your doubles are NOT different from everybody else's doubles.

Obviously, if Distinct() is returning an enumerable of a count of 2 (btw, Console.WriteLine(itemIdCollection.Count()) is sufficient) it is because GetIds() returns an array containing only two distinct doubles.

Your assumptions, they are incorrect.

Will
A: 

Ghost debugging attempt:

Are you generating new random IDs in your GetIds() function? If so, remember you should be instantiating Random outside the function...

John Rasch