Refactor code using LINQ in C#

Asked

Viewed 44 times

0

I need to refactor this method in C# and replace these 3 foreach with something smaller using LINQ:

    public List<Ponto> Filtrar(IQueryable<Ponto> pontosFiltrados, List<Usuario> usuarios)
    {
        var pontosFiltradosPorUsuarios = new List<Ponto>();
        var cont = 0;

        foreach (var ponto in pontosFiltrados)
        {
            foreach (var usuario in usuarios)
            {
                foreach (var pontoUsuario in ponto.Usuarios)
                {
                    if (pontoUsuario.Id == usuario.Id)
                    {
                        cont++;
                    }
                }
            }

            if (cont == usuarios.Count && ponto.Usuarios.Count == usuarios.Count)
            {
                pontosFiltradosPorUsuarios.Add(ponto);
            }

            cont = 0;
        }

        return pontosFiltradosPorUsuarios;
    }

What this method needs to do is return all points that have exactly the user list passed as argument.

The classes User and Dot are below:

public class Usuario
{
    public int Id { get; set; } 
}

public class Ponto
{
    public string Nome { get; set; }
    public int Id { get; set; }
    public List<Usuario> Usuarios { get; set; } 
}

1 answer

1

Eventually there will be another way to do it (which is normal in LINQ), but here goes a solution:

public List<Ponto> Filtrar(IQueryable<Ponto> pontosFiltrados, List<Usuario> usuarios)
{
    return pontosFiltrados
        .Where(r => r.Usuarios.Count == usuarios.Count && r.Usuarios
            .All(x => usuarios
                .Any(y => y.Id == x.Id)))
        .ToList();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.