Answer the question
In order to leave comments, you need to log in
How to find the same elements of an array of objects (in 1 array)?
static object[] arrComputer = {
new Comp { marka = "asus", year = 2004 },
new Comp { marka = "MSI", year = 2002},
new Comp { marka = "Samsung", year = 2003 },
new Comp { marka = "Sony", year = 2002 },
new Comp { marka = "Sony", year = 2004 },
new Comp { marka = "Asus", year = 2012 },
};
Answer the question
In order to leave comments, you need to log in
Assemble the collection, something like this:
var result = new Dictionary<int, List<object>>();
foreach (var item in arrComputer)
{
var c = (Comp)item;
// проверяем, есть такой год в коллекции или нет
if (!result.ContainsKey(c.year))
{
// такого года еще нет, добавляем
result.Add(c.year, new List<object> { c });
}
else
{
// год есть, добавляем запись в него
result[c.year].Add(c);
}
}
// в result будет коллекция: год-компьютеры
foreach (int year in result.Keys)
{
Console.WriteLine
(
"В {0} году на Земле вылупилось компьютеров: {1}",
year,
result[year].Count
);
if (result[year].Count > 1)
{
Console.WriteLine("Да это просто демографический взрыв какой-то!");
foreach (var item in result[year])
{
Console.WriteLine("+ {0}", ((Comp)item).marka);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question