我想统计集合中列表中差异(或相似性)的数量。下面的代码是for循环,它会产生正确的结果,将每个其他记录与第一个记录。 有没有办法做得更好?有了Linq,也许?Linq统计集合中列表中的差异数
public void Main(){
_records = new ObservableCollection<Record>();
_records.Add(new Record { Name = "Correct", Results = new List<string> { "A", "B","C" } , Score="100%"});
_records.Add(new Record { Name = "John", Results = new List<string> { "A", "B" ,"C" } }); //Expect score to be 3/3 (100%)
_records.Add(new Record { Name = "Joseph", Results = new List<string> { "A", "C","B" } }); //Expect score to be 2/3 (67%)
_records.Add(new Record { Name = "James", Results = new List<string> { "C", "C", "C" } }); //Expect score to be 1/3 (33%)
for(int i = 1; i < _records.Count(); i++) // Each Results in the _records except "Correct"
{
float score = _records[0].Results.Count();
_records[i].Score = string.Format("{0:p1}", (score - CountDifferences(_records[i].Results, _records[0].Results))/score);
}
}
private int CountDifferences(List<string> x, List<string> y)
{
return (x.Zip(y, (a, b) => a.Equals(b) ? 0 : 1).Sum());
}
为什么你期望第三笔记录的分数是67%? – Enigmativity
我只能假设你真的意思是约瑟得到33%的分数;正如Enigmativity暗示的那样。因为按索引排列的唯一等级是A.根据这个假设,我给出了一个使用Dictionarys而不是你的自定义类的答案。 – Edward