How to join sublists with Linq

Asked

Viewed 30 times

3

Imagine I have the following classes:

public class Pedido
{
    public int PedidoId { get; set; }
    public List<ItemPedido> Itens { get; set; }
}

public class ItemPedido
{
    public int ItemPedidoId { get; set; }
}

And I need to return all orders with your Chiropractor together with its items with the respective Itempedidoid, this in a single Collection, something like:

var pedido1 = new Pedido() { PedidoId = 1 };
pedido1.Itens.Add(new ItemPedido() { ItemPedidoId = 1 });
pedido1.Itens.Add(new ItemPedido() { ItemPedidoId = 2 });

var pedido2 = new Pedido() { PedidoId = 2 };
pedido2.Itens.Add(new ItemPedido() { ItemPedidoId = 1 });
pedido2.Itens.Add(new ItemPedido() { ItemPedidoId = 2 });

var pedidos = new List<Pedido>();
pedidos.Add(pedido1);
pedidos.Add(pedido2);

// Como fazer aqui? ...
var pedidoItens = from p in pedidos 
                  //select new { p.PedidoId, ? }                        

/* ...Para retornar isso
    * PedidoID, ItemDoPedidoID              
        1     ,   1
        1     ,   2
        2     ,   1
        2     ,   2
*/

What is the best way to achieve this result using Linq?

  • That? https://answall.com/q/80066/101

1 answer

2


I don’t know if using Constains is the best way, since in your Pedido no reference to the ItemPedido, but you can do it this way:

var resultado = from i in pedidos.SelectMany(e => e.Itens)
                from p in pedidos
                where p.Itens.Contains(i)
                orderby p.PedidoId
                select new { p.PedidoId, i.ItemPedidoId };

Browser other questions tagged

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