How to join lists in C #?

5

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 inside the product is empty) and another one of departments, is it possible to relate them? For example, create another list of products with the department objects within the product?

Thank you!

    
asked by anonymous 11.11.2015 / 18:54

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. Itero the list of products. For each product, I look for a department with the product department code.

FirstOrDefault returns the department if it finds the department or null otherwise.

    
11.11.2015 / 18:59
-1

See if that fixes 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);
      }
    
11.11.2015 / 19:01