Avoid duplicate data in list

1

I need a list of musicians without repetitions, but it is bringing duplicate values, according to the amount of songs that each Musician has, how do I bring just one Musician?

public ActionResult SelecaoMusico()
{
    List<Musico> musicos = new List<Musico>();
    Musico musico;
    List<Musica> musicas = db.Musicas.ToList();

    foreach(var musica in musicas){
        int idMusica = musica.MusicaID;
        int musicoIdMusica = musica.MusicoID;

        musico = db.Musico.Where(p => p.MusicoID.Equals(musicoIdMusica)).SingleOrDefault();
        musicos.Add(musico);
    }

    return Json(musicos);
}
    
asked by anonymous 22.11.2016 / 04:16

3 answers

2
public ActionResult SelecaoMusico()
{
    List<Musico> musicos = new List<Musico>();
    Musico musico;
    List<Musica> musicas = db.Musicas.ToList();

    var listaMusicasSemDuplicada = musicas.GroupBy(x => x.MusicoID).Select(y => y.First());
    foreach(var musica in listaMusicasSemDuplicada){
        int idMusica = musica.MusicaID;
        int musicoIdMusica = musica.MusicoID;

        musico = db.Musico.Where(p => p.MusicoID.Equals(musicoIdMusica)).SingleOrDefault();
        musicos.Add(musico);
    }

    return Json(musicos);
}

That way there will be no repetition.

    
22.11.2016 / 12:57
1

I made a for inside another for:

for (int i = 0; i < musicos.Count; i++)
{
    for (int j = i + 1; j < musicos.Count; j++)
    {
        if (musicos[i].PessoaID == musicos[j].PessoaID)
            musicos.Remove(musico);
    }//fim do for j
}//fim do for i

leaving the code like this:

public ActionResult SelecaoMusico()
{
List<Musico> musicos = new List<Musico>();
Musico musico;
List<Musica> musicas = db.Musicas.ToList();

foreach(var musica in musicas){
    int idMusica = musica.MusicaID;
    int musicoIdMusica = musica.MusicoID;

    musico = db.Musico.Where(p => p.MusicoID.Equals(musicoIdMusica)).SingleOrDefault();
    musicos.Add(musico);

for (int i = 0; i < musicos.Count; i++)
{
    for (int j = i + 1; j < musicos.Count; j++)
    {
         if (musicos[i].MusicoID == musicos[j].MusicoID)
             musicos.Remove(musico);
         }//fim do for j
    }//fim do for i
}

return Json(musicos);
}
    
22.11.2016 / 04:57
0

Instead of using logic, you could use classes that implement ISet<T> , HashSet<T> , for example, do not accept duplicates by default being a good option. But it does not work with indexes, if you want to work with them it is good to give a .ToList ().

Reference: link

    
24.11.2016 / 11:29