2014-05-08 53 views
1

你認爲比較整數數組中的值並打印重複項的最佳方法是什麼?更好的方法來比較整數數組中的值

我試着用for循環,但是必須有一種比較簡單的方法來使用方法進行比較。 memcmp/wmemcmp是否適用於此?或者可能是Intersect方法?

這可能是一個noob問題,所以我很感激任何可以幫助我和/或其他人的答案。

英語不是我的母語,請原諒我的打字錯誤。

+3

我建議刪除這個問題,並在CodeReview上貼一個示例代碼。你可能會得到答案。你不會在這裏,因爲這是我們修復破損代碼的地方。請注意,如果你這樣做,代碼必須工作。 – Magus

+0

更好的感覺?最簡潔,最好的表現? – Slugart

回答

3

如果你只是試圖找到在單個陣列中重複,你可以使用LINQ:

int[] duplicates = theArray 
        .GroupBy(i => i) // Group by the value 
        .Where(g => g.Count() > 1) // Filter to groups with >1 element 
        .Select(g => g.Key) // Take out the value 
        .ToArray(); 

如果你想兩個陣列之間找到匹配,使用Intersect

var matches = firstArray.Intersect(secondArray); // Provides elements in both arrays 
0
int[] a = new int[] {6, 9, 3, 4}; 
int[] b = new int[] { 5, 6, 1, 9, 7, 8 }; 
checkDuplicates = a.Intersect(b).Any(); 
+0

我試過了Intersect方法,但是當打印'checkDuplicates'出現並且發現相交時。它打印出真實的。我如何避免這種情況? –