【问题标题】:How to join the result of one query into the result of another without selecting new instance? [duplicate]如何在不选择新实例的情况下将一个查询的结果加入另一个查询的结果? [复制]
【发布时间】:2018-01-29 20:54:36
【问题描述】:

我有一个类,它的数据来自两个不同的来源 - 一个是数据库,另一个是 Web API。
数据库源为我提供了大部分数据,而 Web API 仅提供了一些属性。
我使用 Dapper 从数据库中获取数据,作为 IEnumerable<MyClass>(其中来自 Web API 的属性都是空值), 来自 Web API 的数据是 IEnumerable<WebApiClass>

现在我需要将这两个结果合并到一个 IEnuemrable<MyClass> - 很简单 -

var query = from c in dbResults
            join w in webResults on c.Id equals w.Id
            select new MyClass()
            {
                dbProp1 = c.dbProp1, dbProp2 = c.dbProp2, ...
                waProp1 = w.Prop1, waProp2 = w.Prop2, ...
            }

有没有办法在不选择new MyClass() 的情况下做到这一点,而只需使用dbResults 中已经存在的MyClass 实例?

我见过的所有连接查询都使用 select new - 这真的是唯一的选择吗?

【问题讨论】:

  • 我认为您的问题的措辞可能会有所不同,因为您真正想要的是select c 具有基于w 的更新属性-- 其中有already been asked and answered
  • @MarkC。谢谢,我确实尝试改写我的搜索,但没有出现。
  • 完全没问题

标签: c# linq


【解决方案1】:

使用方法语法连接并显式打开resultSelector 的范围。在其中根据需要编辑对象并将其返回。

var result = dbResults.Join(webResults, db => db.Id, web => web.Id
                            (db, web) => {
                                db.SomePropFromWeb = web.SomeProp;
                                return db;
                            });

【讨论】:

  • 谢谢!明天我会检查欺骗和你的答案,如果我能做到的话,我会接受。
猜你喜欢
  • 2019-09-29
  • 2011-12-02
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 1970-01-01
相关资源
最近更新 更多