我想統計集合中列表中差異(或相似性)的數量。下面的代碼是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