1 つの配列に 2 つ以上の等しい値があるかどうかを確認するにはどうすればよいですか?
例えば。この例では、2 のペアと 4 のペアがあることをプログラムに教えてもらいたい
int[] array1 = { 1, 2, 4, 2, 4 };
Linq の使用
var result = array1.GroupBy(i=>i)
.Select(g=>new {Value = g.Key, Count = g.Count()})
.Where(x=>x.Count>1)
.ToList();
foreach (var pair in result)
{
Console.WriteLine("PAIR: " + pair.Value + " COUNT: " + pair.Count);
}
次のような Linq ステートメントを使用できます。
var query =
from numbers in array1
group numbers by numbers into duplicates
where duplicates.Count() > 1
select new { Item = duplicates.Key, ItemCount = duplicates.Count() };
これにより、以下が返されます。
Item 2: ItemCount 2
Item 4: ItemCount 2
または同じための別の構文:
var query = array1.GroupBy(x => x)
.Where(x => x.Count() > 1)
.Select(x => new { x, Count = x.Count() });
LINQを使用できますGroupBy
例:
var grouped = array1.GroupBy(x => x).Select(x => new { Value = x.Key, Count = x.Count() });
foreach(var item in grouped) {
if (item.Count == 1)
continue;
Console.WriteLine("There are {0} instances of the number {1} in the array.", item.Count, item.Value);
}
私はこの構文が好きです:
int[] array1 = { 1, 2, 4, 2, 4 };
var isThereAnyRepeated = (from i in array1
group i by i into g
where g.Count() > 1
select g).Any();
Console.WriteLine(isThereAnyRepeated);
class item
{
int value;
int number;
}
list<item> items = new list <item>();
for(int i=0; i<array1.length;i++)
{
if (i=0)
items.add(new item(array1[i],1))
else if (array1.contains(array[i])) items.add(new item(array1[i],))
else items.add(new item(array1[i],1))
}