C# 当元素不存在时,将元素添加到数组中

C# 当元素不存在时,将元素添加到数组中,c#,arrays,C#,Arrays,我有一句话: string x = "This is a first string, this is a second string."; 将每个单词添加到数组中时 string[] words = x.Trim().Split(new char[] { ' ' }); 我必须做什么才能在数组中只添加唯一的单词 使用Linq 此外,由于Split采用params数组,因此不需要新的char[]部分 string[] words = x.Trim().Split(' ').Di

我有一句话:

    string x = "This is a first string, this is a second string.";
将每个单词添加到数组中时

    string[] words = x.Trim().Split(new char[] { ' ' });
我必须做什么才能在数组中只添加唯一的单词

使用Linq

此外,由于Split采用params数组,因此不需要新的char[]部分

string[] words = x.Trim().Split(' ').Distinct().ToArray();
使用

你要做的是:

string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();

在将字符串添加到数组之前,可以遍历数组以查看单词是否已经存在

例如:

List<string> arrayStr = new List<string>();

希望这有助于

在一整分钟内以三票优势获得答案,因此决定不告诉我。哎呀。你可能还想用正则表达式或类似的东西去掉任何标点符号,这样你就不会有一个“string”条目和一个“string”条目了。哈哈,你更快了;)这就像:“女士们先生们,启动你们的引擎!”你们还需要处理一个词的不同大小写
List<string> arrayStr = new List<string>();
if(arrayStr.Contains(abc))
MessageBox.Show("Word already exists");
else
arrayStr.Add(abc);