3

这是我的代码:

class Program
    {
        static void Main(string[] args)
        {
            string sentence = string.Empty;
            sentence = Console.ReadLine();
            string[] sent = sentence.Split(' ');
            //to be sorted alphabetically
            var x =
                from k in sent
                orderby k
                select k;

            foreach (string s in x)
            {
                    Console.WriteLine(s.ToLower());
            }

            Console.ReadLine();
        }
    }

有什么方法可以查找和删除重复的单词,或者我应该自己制作方法吗?

4

4 回答 4

11

您可以使用 Linq 的Distinct扩展方法:

var sent = sentence.Split(' ').Distinct();

你也可以在比较字符串时使用它来忽略字符串的大小写——例如"WORD""word"会被认为是重复的:

var sent = sentence.Split(' ').Distinct(StringComparer.CurrentCultureIgnoreCase);
于 2013-10-14T20:37:43.177 回答
8

使用 System.Linq Distinct

foreach (string s in x.Distinct())
于 2013-10-14T20:37:24.297 回答
4

使用不同:

foreach (string s in x.Distinct())
{
        Console.WriteLine(s.ToLower());
}
于 2013-10-14T20:39:46.840 回答
0

这应该可以满足您的所有要求:

class Program
{
    static void Main(string[] args)
    {
        string sentence = string.Empty;
        sentence = Console.ReadLine();

        var sent = sentence
            .Split(' ')
            .Distinct()
            .OrderBy(x => x);

        foreach (string s in sent)
        {
            Console.WriteLine(s.ToLower());
        }

        Console.ReadLine();
    }
}

希望能帮助到你!

于 2013-10-14T20:41:43.180 回答