排行榜与不同的名单

时间:2016-10-25 19:36:17

标签: c# arrays list sorting

我只是想知道,基于这条规则的最佳单词是什么:(单词中的不同字母)^ 2 /(单词中的总字母数)。所以我从一些基本的东西开始

        StreamReader SR = new StreamReader (FILE_PATH);
        int counter = 0;
        string line;

        List<string> words = new List<string> ();
        List<double> points = new List<double> ();

        while ((line = SR.ReadLine ()) != null) {
            short unique = (short)line.Distinct ().ToArray ().Length;
            short total = (short)line.Length;
            double value = (15 * Math.PI * Math.Pow (unique, 2)) / total;

            words.Add (line);
            points.Add (value);

            counter++;
        }

        int Index = points.IndexOf (points.Max ());
        Console.WriteLine ("best: " + words [Index] + " points: " + points [Index]);
    }

但我也想拥有一个带有“最佳”词汇和相对点的排行榜。我有一个想法,需要不同的列表来找出有点的单词,但是有更简单快速的方法吗?

1 个答案:

答案 0 :(得分:0)

我建议使用 Dictionary<string, double> word 及其对应的)而不是 two zipped Lists

Dictionary<string, double> points = File
  .ReadLines(FILE_PATH)
 //.Where(line => !string.IsNullOrEmpty(line)) // you may want to filter out empty lines
  .Select(line => new {
     word = line,
     unique = word.Distinct().Count()
     total = word.Length })
  .ToDictionary(item => item.word, 
                item => 15 * Math.PI * item.unique * item.unique / item.total);

因此,您可以在 Linq 的帮助下轻松实现排行榜:

  var TopTen = points
    .OrderByDescending(pair => pair.Value)
    .ThenBy(pair => pair.Key)
    .Take(10)
    .Select(pair => $"word: {pair.Key} points: {pair.Value}");

  Console.Write(String.Join(Environment.NewLine, TopTen));
相关问题