使用Linq返回每个项仅一次

3

我想要做的是让用户输入一串由空格分隔的数字序列。保存这些数字后,我想返回一个字符串,其中每个数字只出现一次,即使该数字在序列中出现了n次。

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

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

我遇到了这个错误:

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
2个回答

7
扩展方法IEnumerable.Distinct不是一个谓词函数。它作用于IEnumerable<T>并返回一个新的IEnumerable<T>,其中每个元素只出现一次。
要修复您的代码,请使用以下方法:
IEnumerable<string> distinctNumbers = tempNumbers.Distinct();

我想返回一个仅包含所有数字的字符串,每个数字只出现一次

如果你希望结果是一个以单个空格分隔的字符串,那么除了上面所说的方法,你还需要使用 string.Join 方法:

string result = string.Join(" ", distinctNumbers.ToArray());
txtResult.Text = result;

我执行了以下操作,但我没有获得IEnumarable的值,只有类型名称被放置在文本框中。txtResult.Text = distinctNumbers.ToList().ToString(); - Sergio Tapia
@Sergio Tapia:那是因为 List 的 ToString 方法仅显示类型名称,而不是列表的内容。请参见我的答案更新。 - Mark Byers

1

Where(value => value.Distinct())将从tempNumbers中获取每个字符串进行评估。此外,该字符串是一个字符集合。这就是为什么可以将Distinct()应用于

value.

此外,Distinct()扩展方法的结果是IEnumerable<T>,其中T在此处为char。因此整个操作导致异常。

为了获得不同的数字,您可以使用查询

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

干杯


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接