【问题标题】:linq combine 2 tables into one listlinq 将 2 个表合并为一个列表
【发布时间】:2014-02-15 03:33:47
【问题描述】:

我在 db 中有 2 个表 - 一个是 EmploymentRecords 一个是 EmploymentVerificationRecords

我想查询两个表并返回一个列表

我有一个模型(简化示例):

Public Class Record
{
  int ID {get; set;}
  string name {get; set;}
  bool IsVerification {get; set;}
}

我想在 LINQ 中进行某种类型的查询,例如:

  var records = from a in _context.EmploymentRecords
        join b in _context.EmploymentVerificationRecords on a.id equals b.id
        where a.UserID = 1
        select new Record() { .ID = a.id, .name = a.name, .IsVerification = false}
        // I also want to select a new Record() for each b found

请参阅 - 我还希望在第二个表中找到的每条记录的结果中添加一个新的 Record(),因为这些结果 IsVerification 将是 True

【问题讨论】:

    标签: c# sql .net linq


    【解决方案1】:

    您可以从现在选择的 DB 中选择所有内容(但我更愿意使用 join/into 来执行此操作),然后使用 LINQ to Objects 将结果展平为一个大集合。

    以下应该可以解决问题:

    var records
        = (from a in _context.EmploymentRecords
           join b in _context.EmploymentVerificationRecords on a.id equals b.id into bc
           where a.UserID = 1
           select new {
               a = new Record() { ID = a.id, name = a.name, IsVerification = false},
               b = bc.Select(x => new Record() { ID = x.ID, name = b.name, IsVerification = true })
           }).AsEnumerable()
             .SelectMany(x => (new [] { x.a }).Concat(x.b));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-22
      • 2014-08-04
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      相关资源
      最近更新 更多