-4

可能重复:
C# 列格式

好吧,我在我的代码中这个棘手的部分,暂时被卡住了,所以我寻求帮助。我也在用 C# 开发这个。这是我处理它的一段代码:方法显示是我在其他人身上遇到的问题是正确的。问题输出错误,与 for each 循环有关。请看看我的输出现在是什么样子的链接,以及我试图让它看起来像什么的链接

thanks alot guys the question was answered
4

3 回答 3

1

以下是获得所需结果的查询

var dict = items.GroupBy(x=>x.Value).ToDictionary(y=> y.Key, y=> String.Join(" ", y.Select(z=>z.Key)));

要了解上述查询,请参阅groupingToDictionaryString.Join

以下是您修改后的程序

void Main()
    {

        SortedDictionary<string, int> dict =Words();
        display(dict);
        Console.WriteLine();
    }

    private static SortedDictionary<String, int> Words()
    {

        SortedDictionary<string, int> dic = new SortedDictionary<string, int>();

        String input = "today is Wednesday right and it sucks. today how are you are you a rabbit today";
        string[] word = Regex.Split(input, @"\s");

        foreach (string current in word)
        {
            string wordKey = current.ToLower();

            if (dic.ContainsKey(wordKey))
            {
                ++dic[wordKey];
            }
            else
            {
                dic.Add(wordKey, 1);
            }
        }
        return dic;
    }

    private static void display(SortedDictionary<string, int> dictionary)
    {

         var items = from pair in dictionary
                orderby pair.Value descending
                select pair;
        var dict = items.GroupBy(x=>x.Value).ToDictionary(y=> y.Key, y=> String.Join(" ", y.Select(z=>z.Key)));
          foreach (var item in dict)
         {
             Console.WriteLine("Words occurung "+item.Key +" times");
             Console.WriteLine("{0}", item.Value);
         }

        Console.ReadLine();
    }

输出

Words occurung 3 times 
today 
Words occurung 2 times 
are you 
Words occurung 1 times 
a and how is it rabbit right sucks. wednesday
于 2012-11-09T04:35:48.163 回答
1
var max =
    (from pair in dictionary
    select pair.Value).Max()
for (int i = max; i > -1; i--)
{
    var items =
        from pair in dictionary
        where pair.Value == i
        select pair.Key;
    if (items.Count() > 0)
    {
        Console.WriteLine("\nWords occuring " + i.ToString() +" times");
        int count = 0;
        foreach(var item in items)
        {
            if (count == 4)
            {
                Console.WriteLine("");
                count = 0;
            }
            else
            {
                count++;
            }
            Console.Write(item + "\t");
        }
    }   
}

用与此类似的内容替换display方法中的代码应该会返回所需的结果。

于 2012-11-09T04:30:52.707 回答
0

在选择中使用 .Distinct() :

var items = (from pair in dictionary order by pair.Value descending select pair).Distinct();

于 2012-11-09T04:17:19.083 回答