我没有使用SortedLists的经验,并且由于尝试在列表中输入重复的Ints而遇到了错误“已存在具有相同键的条目”。这是我的一种疏忽,认为这不会发生(这很愚蠢)。
该列表如下所示:
("503", "This is a sentence")
("364", "Oh and another one")
("329", "Yes sentences woo!")
("136", "You gets the point")
引发错误的函数是:
protected void buildSummary()
{
scoreCoord2 = -1;
for (int x1 = 0; x1 < results.Length; x1++)
{
SortedList<int, string> paragraphScoreslist = new SortedList<int, string>();
for (int x2 = 0; x2 < results[x1].Length; x2++)
{
scoreCoord2++;
paragraphScoreslist.Add(intersectionSentenceScores[scoreCoord2], results[x1][x2]);
}
var maxValue = paragraphScoreslist.Max(k => k.Key);
string topSentence = string.Empty;
if (paragraphScoreslist.TryGetValue(maxValue, out topSentence))
{
TextboxSummary.Text += topSentence + "\n";
}
}
}
它所中断的特定行是:
paragraphScoreslist.Add(intersectionSentenceScores[scoreCoord2], results[x1][x2]);
排序的列表包含一个段落的句子和程序计算的句子分数。然后,我需要分数最高的句子,但不知道如何处理该错误。
我认为两个句子都为“top”并且输出都以某种方式很好,或者选择其中一个作为top,除非已经有更高的句子了。
最佳答案
您可以创建一个ScoredSentence类,而不是使用SortedList,例如
public class ScoredSentence
{
public string sentence { get; set; }
public int score { get; set; }
public ScoredSentence(string sentence, int score)
{
this.sentence = sentence;
this.score = score;
}
}
然后,您可以将其全部存储在一个列表中,例如
var s1 = new ScoredSentence("this is a sentence", 2);
var s2 = new ScoredSentence("hey there buddy", 4);
var s3 = new ScoredSentence("This is bad", 0);
var scores = new List<ScoredSentence> {s1,s2,s3};
然后,您可以使用
int max = scores.Max(s => s.score);
或找到得分最高的句子
var maxScoredSentence = scores.First(s => s.score == max);
这就是代码中的样子
for (int x1 = 0; x1 < results.Length; x1++)
{
List<ScoredSentence> scoreslist = new List<ScoredSentence>();
for (int x2 = 0; x2 < results[x1].Length; x2++)
{
scoreCoord2++;
scoreslist.Add(new ScoredSentence(results[x1][x2],intersectionSentenceScores[scoreCoord2]));
}
var maxValue = scoreslist.Max(s => s.score);
string topSentence = string.Empty;
TextboxSummary.Text += scoreslist.First(s => s.score == maxValue).sentence + "\n";
}