每个ITERATION的C#

时间:2012-11-09 04:12:53

标签: c#

  

可能重复:
  C# Column formatting

我很好地处理我的代码中这个棘手的部分并且暂时停留,所以我要求一些帮助。我也在用C#开发它。这是我的代码处理它: 方法显示是我遇到的问题是对的。问题输出是错误的,并且与每个循环有关。请看看我的输出现在的样子链接以及我试图让它看起来像什么的链接

thanks alot guys the question was answered

3 个答案:

答案 0 :(得分: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方法中的代码应返回所需的结果。

答案 1 :(得分: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

答案 2 :(得分:0)

在select:

中使用.Distinct()

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