C# 数组中没有重复项

我有一个包含很多句子的文件。我需要用那个文件中的单词制作一本字典。到目前为止,我已经使用Split()和Sort()方法分离了单词并对其进行了排序。我的问题是制作一个没有重复单词的列表。我怎样才能做到这一点?


static int n = 0;


public static string[] NoDuplicate(string[] array)

{

    int i;

    string[] res = (string[])array.Clone();

    for (i = 0; i < array.Length-1; i++)

    {

       if (array[i + 1] != array[i])

            res[n++] = (string)array[i];

    }

    return res;

}

我怎样才能做得更整洁?

我不喜欢那个方法,因为它是用 Clone() 初始化的,而且长度太大了。


烙印99
浏览 206回答 3
3回答

米琪卡哇伊

除了LINQ的特性之外,您还可以使用HashSet.Distinct():HashSet: 这是一个优化的集合集合。它有助于消除数组中的重复字符串或元素。它是一个散列其内容的集合。public static string[] NoDuplicate(string[] array){&nbsp; &nbsp; string[] result = new HashSet<string>(array).ToArray();&nbsp; &nbsp; return result;}如果要消除不区分大小写的重复项,可以传递如下IEqualityComparer参数:使用HashSet:public static string[] NoDuplicate(string[] array){&nbsp; &nbsp; string[] result = new HashSet<string>(array, StringComparer.OrdinalIgnoreCase)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToArray();&nbsp; &nbsp; return result;}使用 LINQ 的Distict功能:public static string[] NoDuplicate(string[] array){&nbsp; &nbsp; string[] result = array.Distinct(StringComparer.OrdinalIgnoreCase)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToArray();&nbsp; &nbsp; return result;}

炎炎设计

试试这个:private static string[] NoDuplicate(string[] inputArray){&nbsp; &nbsp; var result = inputArray.Distinct().ToArray();&nbsp; &nbsp; return result;}

九州编程

而不是字典创建一个词组。如果重复,则在每个级别保持相同单词的计数。通过这种方式,您可以避免使用太多空间,搜索任何单词 O(log(n)) 会更快,其中 n 是不同单词的数量public&nbsp; class WordList {&nbsp; &nbsp; private int sameWord&nbsp; &nbsp; &nbsp; &nbsp; = 0;&nbsp; &nbsp; String name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= "";&nbsp; &nbsp; WordList [] child = new WordList[26];&nbsp; &nbsp; public&nbsp; void add( String s, WordList c, int index )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; sameWord++;&nbsp; &nbsp; &nbsp; &nbsp; if(index > 0)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name += ""+s.charAt(index-1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(index == s.length())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(c.child[s.charAt(index)-'a'] ==null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.child[s.charAt(index)-'a'] = new WordList();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; add(s,c.child[s.charAt(index)-'a'],index+1);&nbsp; &nbsp; }&nbsp; &nbsp; public static WordList findChar(char c)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return child[(int)(c-'a')];&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP