C# LINQ - 基于集的操作

本文关键字:操作 于集 LINQ | 更新日期: 2023-09-27 18:35:08

我有一个IQueryable列表,其中包含5个字段。 其中4个来自DB。第 5 个字段必须使用 join 语句从代码中分配(由几个不是引用到此表的外键的其他表)。

查询如下所示。

Profile对以下字段进行分类。

Id, Name, Username, Email, Product

产品字段不在数据库中。必须使用以下查询在 C# 代码中填充它。

  var resultSet = (from a in Profiles
                   join _b_ in billingPeriodIncludes
                   on a.Id equals (int?) _b_._cbp.BundleId into b_
                   from _b in b_.DefaultIfEmpty()
                   where a.Product != null
                   select new
                   { 
                     a,
                     Product = (_b != null && _b._p != null) ? (_b._p) : a.Product
                   }

该查询为我提供了配置文件和产品的组合。现在,我遍历每个配置文件并将每个产品分配给其配置文件。

有人可以帮助我直接将产品分配给配置文件吗?

像这样的东西,(不起作用)

var q1 = (from a in Profiles
          join _b_ in billingPeriodIncludes
          on a.Id equals (int?) _b_._cbp.BundleId into b_
          from _b in b_.DefaultIfEmpty()
          select
          //Assign products to the set. Query the set in a separate query.
          a.Product = (_b != null && _b._p != null) ? (_b._p) : a.Product
          );
var q2 = from _q2 in q1 select _q2;

C# LINQ - 基于集的操作

试试这个:-

var resultSet = (from a in Profiles
                 join _b_ in billingPeriodIncludes
                 on a.Id equals (int?) _b_._cbp.BundleId into b_
                 from _b in b_.DefaultIfEmpty()
                 where a.Product != null
                 select new Profiles
                 { 
                    Id = a.Id,
                    Name = a.Name,
                    Username = a.Username,
                    Email = a.Email,
                    Product = (_b != null && _b._p != null) ? (_b._p) : a.Product
                 };

可以直接绑定Profiles对象,而不是anonymous类型。