Using Linq to return each item only once
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开发者_C百科 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
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;
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
精彩评论