LINQ to Objects连接两个集合以在第一个集合中设置值 [英] LINQ to Objects Join two collections to set values in the first collection
问题描述
我有以下实体框架查询:
I have the following Entity Framework query:
var results = from r in db.Results
select r;
我正在使用AutoMapper映射到另一种类型:
I'm using AutoMapper to map to another type:
var mapped = Mapper.Map<IEnumerable<Database.Result>, IEnumerable<Objects.Result>>(results);
在我的Objects.Result类型中,我有一个名为reason的属性,该属性不是来自数据库.它来自另一个需要基本填充回映射类型的来源:
In my Objects.Result type, I have a property called reason that is not coming from the database. It is coming from another source that I need to basically populate back into my mapped type:
var reasons = new List<Reason>
{
new Reason { Id = 1, Reason = "asdf..." }
};
我需要将原因与我的映射集合一起加入,并使用我的原因集合中的值在映射集合中设置Reason属性.这可能吗?
I need to join the reasons with my mapped collection and set the Reason property in my mapped collection using the value from my reasons collection. Is this possible?
// need something like this:
mapped = from m in mapped
join r in reasons on m.Id equals r.Id
update m.Reason = r.Reason
select m;
显然上述代码无法编译,但是我可以编写满足我要求的代码吗?
Obviously the above code doesn't compile, but is there code I can write that does what I want?
推荐答案
循环进行突变.理想情况下,Linq应该对其操作的集合没有任何变异.使用Linq筛选,排序,投影数据,使用传统技术进行修改.
Do the mutation in a loop. Optimally, Linq should be free of mutations to the collection(s) it operates against. Use Linq to filter, order, project your data, use traditional techniques to modify.
var joinedData = from m in mapped
join r in reasons on m.Id equals r.Id
select new { m, r };
foreach (var item in joinedData)
{
item.m.Reason = item.r.Reason;
}
这篇关于LINQ to Objects连接两个集合以在第一个集合中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!