【问题标题】:Merging result of two queries合并两个查询的结果
【发布时间】:2012-05-18 10:57:08
【问题描述】:

我正在做两个查询:

Dim worker = (From p in db.workers where p.dateAdded > today 
                   select new with{.name = p.name, .desc = p.description})

Dim client = (From p in db.clients where p.dateAdded > today 
                   select new with{.name = p.name, .desc = p.description})

如何将这两个查询合并为只有一个可以用作DataSource

【问题讨论】:

  • workers 和 clients 表之间是否有任何关系(如外键)?
  • 不,这只是我想添加到另一个查询
  • 如果您仍有问题,请使用更多代码和场景更新帖子。所以我们可以为您提供帮助。

标签: asp.net vb.net linq


【解决方案1】:

试试这样的

   Dim Merged = (From p in db.workers where p.dateAdded > today 
                       select new with{.name = p.name, .desc = p.description})
                 .Union
                 (From p in db.clients where p.dateAdded > today 
                       select new with{.name = p.name, .desc = p.description})

【讨论】:

  • 我认为它会成功,但它不能将 System.Data.Linq.DataQuery` 转换为 System.Collections.Generic.IEnumerable... 有什么想法吗?
【解决方案2】:

如果想要获得不同的结果,请使用Distinct

var merged = worker.Concat(client).Distinct();

var mergedList = worker.Union(client).ToList();

【讨论】:

  • 我很确定他想加入这些查询。不会对你投反对票,因为他的问题模棱两可。这是一个编辑。 Concat,对,是一种加入 ^_^ 暂时忽略了这一点
  • 他要求联合,因为两个 linq 结果中的属性相同,并且没有列看起来像主键来连接这两个结果。
  • @Romil:如果 workersclients 没有相同的列,这会起作用吗??
  • 如果两个结果的数据类型和列数不同,则无法进行 UNION 和合并。
  • @Romil:当然,那么你必须在你的回答中提到这一点,因为这并不适用于所有情况!!!
【解决方案3】:

你能具体说明你想要做什么吗?
1。将结果合并为一组 - 如果是,您可以使用 huMpty duMpty's 提议
2。如果您想使用两个带有 Linq 查询的 DataTable 执行类似于 DataSet 的操作,我不确定这是否可以实现。

希望这会有所帮助!

【讨论】:

    【解决方案4】:

    使用Union,它提供了您的预期结果。

    看看Return the Set Union of Two Sequences (LINQ to SQL)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-05
      • 2016-10-27
      • 2022-06-16
      • 2013-07-25
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      相关资源
      最近更新 更多