V
V
Vitaly2016-12-02 22:49:22
Programming
Vitaly, 2016-12-02 22:49:22

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 },
            };

How can I find elements with the same release year in this array?
Only I use only cycles, without LINQ.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Nemiro, 2016-12-02
@AlekseyNemiro

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);
    }
  }
}

Instead of object , you can immediately use Comp if you do not intend to use other types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question