Dis*_*ile 21 .net c# linq-to-objects
我有以下实体框架查询:
var results = from r in db.Results
select r;
Run Code Online (Sandbox Code Playgroud)
我正在使用AutoMapper映射到另一种类型:
var mapped = Mapper.Map<IEnumerable<Database.Result>, IEnumerable<Objects.Result>>(results);
Run Code Online (Sandbox Code Playgroud)
在我的Objects.Result类型中,我有一个名为reason的属性,它不是来自数据库.它来自另一个来源,我需要基本填充回我的映射类型:
var reasons = new List<Reason>
{
new Reason { Id = 1, Reason = "asdf..." }
};
Run Code Online (Sandbox Code Playgroud)
我需要使用我的映射集合加入原因,并使用my reason集合中的值在我的映射集合中设置Reason属性.这可能吗?
// 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;
Run Code Online (Sandbox Code Playgroud)
显然上面的代码没有编译,但是我能编写的代码可以做我想要的吗?
Ant*_*ram 24
在循环中进行突变.最理想的情况是,Linq应该没有针对其运作的集合的突变.使用Linq过滤,排序,投影数据,使用传统技术进行修改.
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;
}
Run Code Online (Sandbox Code Playgroud)
Tow*_*hin 10
这可能会节省您的大量时间.下面的代码用于加入两个集合并设置第一个集合的属性值.
class SourceType
{
public int Id;
public string Name;
public int Age { get; set; }
// other properties
}
class DestinationType
{
public int Id;
public string Name;
public int Age { get; set; }
// other properties
}
List<SourceType> sourceList = new List<SourceType>();
sourceList.Add(new SourceType { Id = 1, Name = "1111", Age = 35});
sourceList.Add(new SourceType { Id = 2, Name = "2222", Age = 26});
sourceList.Add(new SourceType { Id = 3, Name = "3333", Age = 43});
sourceList.Add(new SourceType { Id = 5, Name = "5555", Age = 37});
List<DestinationType> destinationList = new List<DestinationType>();
destinationList.Add(new DestinationType { Id = 1, Name = null });
destinationList.Add(new DestinationType { Id = 2, Name = null });
destinationList.Add(new DestinationType { Id = 3, Name = null });
destinationList.Add(new DestinationType { Id = 4, Name = null });
var mapped= destinationList.Join(sourceList, d => d.Id, s => s.Id, (d, s) =>
{
d.Name = s.Name;
d.Age = s.Age;
return d;
}).ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34146 次 |
| 最近记录: |