2011-11-14 83 views
15

我有以下實體框架查詢:LINQ到對象加入兩個集合的第一個集合中設置值

var results = from r in db.Results 
       select r; 

我使用AutoMapper映射到另一種類型:

var mapped = Mapper.Map<IEnumerable<Database.Result>, IEnumerable<Objects.Result>>(results); 

在我的Objects.Result類型,我有一個名爲理由不是來自數據庫的屬性。

var reasons = new List<Reason> 
{ 
    new Reason { Id = 1, Reason = "asdf..." } 
}; 

我需要用我的映射集合到一起的原因,並利用我的理由的價值在我的映射集設置的原因屬性:它是從我需要基本填充回我的映射類型其他來源來採集。這可能嗎?

// 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; 

很明顯,上面的代碼不能編譯,但有代碼我可以寫,做我想要的嗎?

回答

21

在循環中做突變。理想情況下,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; 
} 
+0

謝謝。我猜是性能方面,這不是一個巨大的命中,因爲我在映射之前分頁數據,所以第二次迭代不會成爲問題。 – Dismissile

+0

如果您測量並發現這是一個性能瓶頸,請回過頭來解決它,如果我們*有*到*,我們可以*做出變異。但是,我不會那樣做,直到我知道這是什麼讓我放慢腳步。 –

+0

我每頁約10個項目。我非常懷疑它會導致任何性能問題:) – Dismissile

0

一種蠻力方法是: -

foreach(var m in mapped) 
{ 
    m.Reason = reasons.Single(r=> r.Id == m.Id).Reason; 
} 

其實,這是實現相當接近你的僞代碼。

5

這樣可以節省很多時間。 以下代碼用於加入兩個集合並設置第一個集合的屬性值。

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(); 
+1

你應該解釋它在做什麼。 –