c# linq - 基于集合的操作

标签 c# asp.net asp.net-mvc linq

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

查询看起来像这样。

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;

最佳答案

试试这个:-

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
                 };

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

关于c# linq - 基于集合的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27636112/

相关文章:

c# - ASP.NET MVC 的路由调试器

javascript - 使用 MVC 和 AngularJS 时模板不同部分的布局和设计

css - MVC5 bundle 不适用于某些资源

c# - Graphics.DrawImage 意外调整图像大小

c# - Elasticsearch NEST向现有索引添加属性

c# - 关闭 Form2 并显示 Form1

javascript - 无法确定单选按钮是否被选中

c# - 表单提交后清除(重置)表单字段(数据)

asp.net-mvc - asp.net mvc 3 预选 Html.DropDownListFor 不在 Nerd 晚餐中工作

c# - Firebird 错误: "operating system directive CreateFile failed" on opening connection