0

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,

4
  • 1
    what were you expecting it to return and why? Commented May 3, 2010 at 13:31
  • Have you ever looked at the content of dIds? Commented May 3, 2010 at 13:33
  • 2
    Why is count written with a lowercase C? Is this your real code? Commented May 3, 2010 at 13:34
  • Are you using doubles as Ids? Floating point numbers and equality are not great friends... Commented May 3, 2010 at 13:39

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();

5 Comments

ForEach extension doesn't belong to .Net standard libraries...you should provide it (even if very simple to find or implement)
ForEach is an extension on Lists provided with Linq as part of .NET.
Sorry, I dislike it so much that I've forgotten its esistence. :P
ForEach is not an extension on lists and is not a part of LINQ. It's a perfectly ordinary method on the list type.
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
0

Ghost debugging attempt:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.