有没有办法可以在C#中从数组中返回重复值?我也想写一个小算法,它会返回一个数组中最多的重复值。例如
[1,2,2,2 3,3]我需要返回具有最多出现次数和出现次数的重复值。
我想我看到一些帖子说可以使用Linq完成,但我不知道Linq是什么
非常感谢任何帮助。
答案 0 :(得分:4)
试试这个:
int[] data = new int[] { 1, 2, 2, 2, 3, 3 };
IGrouping<int, int> mostOccurrences = data
.GroupBy(value => value)
.OrderByDescending(group => group.Count())
.First();
Console.WriteLine("Value {0} occurred {1} time(s).", mostOccurrences.Key, mostOccurrences.Count());
请注意,如果多个值出现的次数相同(例如,如果您在该列表中添加了另外3个值),则上述代码将仅列出其中一个值。要处理这种情况,请尝试以下方法:
int[] data = new int[] { 1, 2, 2, 2, 3, 3, 3 };
var occurrenceInfos = data
.GroupBy(value => value)
.Select(group =>
new {
Count = group.Count(),
Value = group.Key
}
);
int maxOccurrenceCount = occurrenceInfos.Max(info => info.Count);
IEnumerable<int> maxOccurrenceValues = occurrenceInfos
.Where(info => info.Count == maxOccurrenceCount)
.Select(info => info.Value);
foreach (int value in maxOccurrenceValues)
Console.WriteLine("Value {0} occurred {1} time(s).", value, maxOccurrenceCount);
答案 1 :(得分:2)
以下是我对此的看法:
var data = new[] { 1, 2, 2, 2, 3, 3, };
var occurences =
data
.ToLookup(x => x)
.ToDictionary(x => x.Key, x => x.Count());
var mostOccurences =
occurences
.OrderByDescending(x => x.Value)
.First();
这些将为您提供以下结果: