2015-02-06 50 views
-1

我是C#的新手,並且在各處搜索了此內容,但如果已經詢問,找不到答案。我試圖用一個for循環來比較兩個列表:在兩個列表中發現不同的匹配<string>

IList<string> List1 = new List<string> { usr.User1, usr.User2, usr.User3, usr.User4 }; 

IList<string> List2 = new List<string>{ "Tim", "Bob", "Brian", "Paul" }; 

基本上我想那裏只有4點可能的匹配,所以只有這些可能的匹配應該算:

usr.User1 == "Tim", // e.g. User1 has to be Tim etc. 
usr.User2 == "Bob", 
usr.User3 == "Brian", 
usr.User4 == "Paul" 

我將理想喜歡用0-4的值返回一個int,因此,如果所有的比賽的上面有成功,那麼它將返回4,如果沒有成功匹配則返回0等

我曾嘗試:

int score = 0; 

for (int i = 0; i <= List2.Count; i++) 
{ 
    if (List1[i] == List2[i]) 
    { 
     score++; 
    } 
} 

但目前正在取得IndexOutOfRangeException。非常感謝。

+0

異常的原因是'<= List2.Count'。如果count爲4,則有效索引值爲0,1,2和3. – 2015-02-06 16:27:25

+0

@ User9876867歡迎使用堆棧溢出。您的問題非常接近[XY問題](http://meta.stackexchange.com/a/66378/171858)。在你的例子中,你正在問如何使用不僅不需要的[tag:for-loop]來完成它,但是有更好的方法來解決實際問題,這很簡單*如何通過索引匹配列表中的值*。 – 2015-02-06 16:33:56

+0

嗨我被告知使用for循環,因爲它更具人性化可讀性和可調試性。 – 2015-02-06 16:38:31

回答

5

刪除=,你想要停止上限。

for (int i = 0; i < List2.Count; i++) 

另一種選擇是使用zip linq

int score = List1.Zip(List2, (a,b) => a == b ? 1 : 0).Sum(); 
+0

這看起來很熟悉:http://stackoverflow.com/questions/28355314/linq-query-to-compare-2-liststring-for-distinct-matches/28355379#28355379 – itsme86 2015-02-06 16:35:38

+1

這是值得注意的(看起來好像海報是新的到C#)集合是基於'0'的。 'Count'屬性是基於'1'的。 – Cameron 2015-02-06 16:42:16

+0

@ itsme86純粹的巧合。偉大的思想和所有的! – weston 2015-02-06 17:23:03

2

輸掉=它應該是for (int i = 0; i < List2.Count; i++)

雖然可能有更好的方法。

0

由於List2有4個元素,當你做出i <= List2.Count語句for循環List2.Count將eqal到4

,你允許循環索引0-4,因爲列表是0索引基礎,當循環得到索引4時,會拋出一個IndexOutOfRangeException異常。

解決方法是將for循環中的<=語句更改爲<

+0

歡迎來到StackOverflow。您可能想查看[格式指南](http://stackoverflow.com/help/formatting)。這將幫助您的問題和答案看起來更好,最終變得更有幫助。另外,我們強烈建議使用其他人發佈的「完整」答案。 :) – Cameron 2015-02-06 16:38:53

+0

謝謝@Cameron,我會採取你的建議。 – 2015-02-06 17:14:38