views:

76

answers:

2

Here's what I'm trying to do. Have a use right a sequence of numbers delimited by spaces. After I save those numbers, I want to return a string of all the numbers only once, even if a number has appeared n number of times in the sequence.

string[] tempNumbers = textValue.Split(' ');

IEnumerable<string> distinctNumbers = tempNumbers.Where(value => value.Distinct());

I'm getting this error:

Error   2   Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<char>' to 'bool' c:\users\sergio\documents\visual studio 2010\Projects\LinqPlayground\LinqPlayground\SetSemanticsExample.cs  67  75  LinqPlayground
+5  A: 

The extension method IEnumerable.Distinct is not a predicate function. It operates on an IEnumerable<T> and returns a new IEnumerable<T> where each element appears only once.

To fix your code just do this instead:

IEnumerable<string> distinctNumbers = tempNumbers.Distinct();

I want to return a string of all the numbers only once

If you want the result as a single space-separated string then in addition to the above you will also need to call string.Join:

string result = string.Join(" ", distinctNumbers.ToArray());
txtResult.Text = result;
Mark Byers
I do the following but I do not get the values of the IEnumarable, only the type name is placed in the textbox. txtResult.Text = distinctNumbers.ToList().ToString();
Sergio Tapia
@Sergio Tapia: That is because a List's ToString method displays only the type name, not the contents of the list. See my update to the answer.
Mark Byers
+1  A: 

Where(value => value.Distinct()) will take each string from the tempNumbers to evaluate. Besides, the string is a collection of chars. That's why you can apply the Distinct() to the

value.

Moreover the result of Distinct() extension method is and IEnumerable<T>, where T is char here. Hence the whole operation causes the exception.

In order to get distinct numbers , you can use the query

var distinctNumbers = (from elem in tempNumbers
                      select elem).Distinct();

Cheers

DrakeVN