3 回答

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個贊
你可以試試HashSet<int>,例如
int[,] arr = new int[3, 3] {
{1, 2, 6 },
{4, 1, 5 },
{6, 1, 8 }
};
HashSet<int> unique = new HashSet<int>();
foreach (var item in arr)
if (!unique.Add(item))
Console.WriteLine(item); // Not unique, print it out
結(jié)果:
1
6
1
如果我們想打印每個副本一次,我們可以添加另一個HashSet<int>:
HashSet<int> unique = new HashSet<int>();
HashSet<int> duplicates = new HashSet<int>();
foreach (var item in arr)
if (!unique.Add(item))
duplicates.Add(item);
foreach (var item in duplicates)
Console.WriteLine(item);
最后,如果您想計算重復(fù)出現(xiàn)的次數(shù),我們可以更改HashSet<int> duplicates為Dictionary<int, int> duplicates:
HashSet<int> unique = new HashSet<int>();
Dictionary<int, int> duplicates = new Dictionary<int, int>();
foreach (var item in arr)
if (!unique.Add(item))
if (duplicates.TryGetValue(item, out int count))
duplicates[item] = count + 1;
else
duplicates[item] = 2;
foreach (var item in duplicates)
Console.WriteLine($"{item.Key} appears {item.Value} times");
編輯:您可以將foreach循環(huán)更改為嵌套 for循環(huán),例如:
所有重復(fù)項(xiàng)
for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
if (!unique.Add(arr[i, j]))
Console.WriteLine(arr[i, j]);
Distinct duplicates
HashSet<int> duplicates = new HashSet<int>();
for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
if (!unique.Add(arr[i, j]))
if (duplicates.Add(arr[i, j])) // print distinct duplicate only
Console.WriteLine(arr[i, j]);

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個贊
或許是這樣的:
var arr = new int[3, 3]{{1,2,6}, {4,1,5}, {6,1,8}}; var duplicates = arr .Cast<int>() .GroupBy(n => n) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToArray();
.Cast<int>()
使數(shù)組可用于 LINQ,.GroupBy(n => n)
按值對數(shù)字進(jìn)行分組,.Where(g => g.Count() > 1)
計算組中的項(xiàng)目數(shù),.Select(g => g.Key)
僅返回組鍵 - 原始值。
.Where(g => g.Count() > 1).Select(g => g.Count())
返回每個的計數(shù),或者根據(jù)需要對組進(jìn)行操作。

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個贊
效率不高,但您也可以將計數(shù)存儲在字典中,然后打印計數(shù)大于 1 的鍵:
var counts = new Dictionary<int, int>();
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
var number = arr[i, j];
if (!counts.ContainsKey(number))
{
counts[number] = 0;
}
counts[number] += 1;
}
}
foreach (var pair in counts)
{
if (pair.Value > 1)
{
Console.WriteLine(pair.Key);
}
}
// 1
// 6
- 3 回答
- 0 關(guān)注
- 216 瀏覽
添加回答
舉報