LINQ to Objects连接两个集合以在第一个集合中设置值

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)

  • 你应该解释一下这是做什么的. (2认同)
  • 正是我所需要的......它正在做的是在连接数据上构建一个语句 lambda,其中语句正在修改并从连接返回目标对象。注意:这只能直接与 LINQ to Objects 一起使用,而不是与 LINQ to SQL 一起使用,因为后者需要表达式树类型 (Expresson&lt;Func&lt;TSource, TResult&gt;),而前者需要委托类型 (Func&lt;T, Tresult&gt;) 。我需要将 EF DbSet 与基于 POCO 的 DTO 联接起来,并且可以通过在联接之前添加“.AsEnumerable”来强制 IQueryable (LINQ to SQL) 为 IEnumerable (LINQ to Objects) 来实现这一点 (2认同)