我有这段代码:
public List<int> Duplicates(List<int> sequence)
{
int[] countArr = new int[156];
foreach (int i in sequence)
{
countArr[i]++;
}
List<int> resultList = new List<int>();
for (var i = 0; i < countArr.Length; i++)
{
if (countArr[i] > 1)
{
resultList.Add(i);
}
}
return resultList;
}
这让我得到了重复的元素,但没有重复这些元素的重复次数。
提前感谢您提供的任何帮助。
修改
我不想使用LINQ
答案 0 :(得分:2)
使用GroupBy:
sequence.GroupBy(i => i).Select(g => new {Value = g.Key, Amount = g.Count()})
如果你不想使用Linq(为什么???),只需在元组中收集价值和金额:
List<Tuple<int,int>> resultList = new List<Tuple<int,int>>();
for (var i = 0; i < countArr.Length; i++)
{
if (countArr[i] > 1)
{
resultList.Add(Tuple.Create(i, countArr[i]));
}
}
答案 1 :(得分:2)
这是一种非常复杂的使用方法,我宁愿返回Dictionary<int, int>
:
public static Dictionary<int, int> Duplicates(IEnumerable<int> sequence)
{
var duplicates = new Dictionary<int, int>();
foreach (int i in sequence)
{
if(duplicates.ContainsKey(i))
duplicates[i]++;
else
duplicates.Add(i, 1);
}
return duplicates;
}
答案 2 :(得分:0)
简单回答字典:
void Main()
{
List<int> intlist = new List<int>
{
1,
1,
1,
2,
2,
3,
4,
4,
4,
4
};
var dict = new Dictionary<int, int>();
foreach (var item in intlist)
{
if (!dict.ContainsKey(item)) // this checks for the existance of an item
{
dict.Add(item, 0); // this initialises the item in the dictionary
}
dict[item]++; // this will update the count of the item
}
// this is just for linqpad debug output and shows each value and their count
// this can be achieved with foreach
dict.Select(x => new { x.Key, x.Value}).Dump();
}
是的我知道底部有一个Select
,但这与重复的集合无关。