左外连接扩展方法linq

时间:2019-03-20 11:01:57

标签: c# linq

我会使用扩展方法翻译此查询 我也将使用扩展方法在单个查询中合并此查询

var variants = _ctx.Varianti.Where(i=>i.attivo==0);

var allProducts = await (from p in  _ctx.Articoli
                         where  p.cat==1
                         join v in variants on p.code equals v.code into gj
                         from articoli in gj.DefaultIfEmpty()
                         select new {
                           Codart = p.Codart,
                           Codvar = articoli.Codvar,
                        }).ToListAsync(); 

我的课程

Articolo类{     公共字符串Codart // key     公开双重价格 }

瓦里安特级{     公共字符串Codart // key     公共字符串Codvar //键     大众国际 }

我必须像这样退货

Prod1-Variant1 Prod2-(无变体) prod3-Variant1 prod4-Variant1 prod4-Variant2 prod5-(无变体)

我应该仅过滤attivo == 0的变体 如果没有的话,所有没有变体的产品

代码运行良好,但我需要在单个查询中对数据库进行优化 以及扩展方法

在T-Sql中应该这样:

SELECT Codart,
       Codvar
  FROM dbo.Articoli
       LEFT OUTER JOIN dbo.Varianti
           ON dbo.Articoli.Codart = dbo.Varianti.Codart
 WHERE (Cat = 1)
   AND (attivo = 0)

1 个答案:

答案 0 :(得分:-1)

我仍然不确定是什么问题。这里有一些示例,说明如何“左-外-联接”产品和变体并选择一个新对象。

List<Articolo> products = new List<Articolo>()
{
    new Articolo() { Code = "1", price = 1 },
    new Articolo() { Code = "2", price = 1 },
    new Articolo() { Code = "3", price = 1 },
    new Articolo() { Code = "4", price = 1 },
    new Articolo() { Code = "5", price = 1 },
};

List<Variante> variants = new List<Variante>()
{
    new Variante() { Code = "1", attivo = 0, Codvar = "v1" },
    new Variante() { Code = "3", attivo = 0, Codvar = "v1" },
    new Variante() { Code = "4", attivo = 0, Codvar = "v1" },
    new Variante() { Code = "4", attivo = 0, Codvar = "v2" },
    new Variante() { Code = "5", attivo = 1, Codvar = "v2" },
};

var result = products // Our "Left"-List 
    .GroupJoin( // Join to a "one"-to-"null or many"-List
        variants.Where(v => v.attivo == 0), // Our "right"-List
        p => p.Code, // select key in left list
        v => v.Code, // select key in right list
        (p, v) => // for every product "p" we have a list of variants "v"
            v.Any() ? // do we have vriants for our product?
                v.Select(s =>  new // for every variant we build our new product
                {
                    Code = p.Code,
                    FirstVariant = s.Codvar,
                })
                : // if we got no variants, we build a "no variant"-product
                new[] { new {
                    Code = p.Code,
                    FirstVariant = "No Variant"
                } } // here we got a list of product-variants per product ("list of lists")
            ).SelectMany(s => s); // We want one list of all product variants

foreach (var item in result)
{
    Console.WriteLine("Code: {0}, FirstVar: {1}", item.Code, item.FirstVariant);
}