How to join lists in c#?

Asked

Viewed 938 times

6

I have two classes:

public class Produto
{
    public int ProCodigo { get; set; }

    public string ProNome { get; set; }

    public int DepCodigo { get; set; }
    public virtual Departamento Departamento { get; set; }

}

public class Departamento
{
    public int DepCodigo { get; set; }

    public string DepNome { get; set; }
}

If I make two lists: one of products (where the department object within the product is empty) and another of departments, is it possible to relate them? For example, create another list of products with the department objects within the product?

Thank you!

  • you said you get the list as json, have an example of json and which library you use to deserialize? Maybe at the time of doing this you can already assemble the list with the right relationships more efficiently.

2 answers

4


Yes:

foreach (var produto in listaProdutos)
{
    produto.Departamento = listaDepartamentos.FirstOrDefault(d => d.DepCodigo == produto.DepCodigo);
}

I suppose listaProdutos the list of products and listaDepartamentos the list of departments. I’m looking for a department with the product code. I’m looking for a department with the product code.

FirstOrDefault returns the department if you find the department or null otherwise.

  • Got it, is that I get this product list by Json so it does not add the departments to the products. So this is the only way?

  • I wouldn’t say the only way. I’d say the right way.

-1

See if that works for you:

List<int> lista1 = new List<int>();
      lista1.Add(1);
      lista1.Add(5);

      List<int> lista2 = new List<int>();
      lista2.Add(6);
      lista2.Add(9);
      lista2.Add(1);

      List<int> lista3 = new List<int>();

      foreach (int i in lista1.Where(c => lista2.Contains(c)))
      {
        lista3.Add(i);
      }

Browser other questions tagged

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