c# – How to traverse an enumerable list and check if the property repeats in the list during foreach loops

Question:

I have a list ( IEnumerable ) called People that contains the properties Id, DataNasc, etc… I need to bring this data to a listview in the html using Razor (or it can be outside the cshtml page, in the .cs files).

Let's say person 1 has

Id 1, Date of Birth 03/23/2000;

And person 2 (displayed in the second round of foreach in the view) has:

Id 2, and DateNasc 03/23/2000;

Since the DateNasc is the same in person 1 and 2…

I would like to make a query like: "if the value of the BirthDate property, in the People list is the same for several people, return all those people who were born on that same day".

Can someone help me?

I'm using C# Asp.Net MVC 4 with Razor View.

I'm new to C#, I was trying to do this, which I think about it doesn't make much sense, but I'm putting it to maybe try to illustrate what I wanted, albeit with the wrong logic.

@foreach (var item in Model.Pessoas)
{
    for (int i = 0; i < Model.Pessoas.Count(); i++)
    {
        var arr = Model.Pessoas.ToArray();
        if (item.DataNasc == arr[i].DataNasc)
        {
            <p>@arr[i].DataNasc</p>
        }
    }
}

Answer:

Good evening, have you thought about using a Dictionary<> dictionary? You can use a DateTime as a key and a list of the List<Pessoa> class people as a value.

Example:

Dictionary<DateTime, List<Pessoa>> comMesmaData;
// Para checar se já há pessoas com esta data ou inserir novas!!!
if (comMesmaData.Conteins(DATA))
    comMesmaData[DATA].Add(NOVA_PESSOA);
else
    comMesmaData.Add(DATA, NOVA_PESSOA);

At the end you will have all the data of the people grouped by date.

Scroll to Top