2011-10-25 204 views
5

System.Linq.Enumerable.WhereListIterator的區別是什麼& System.Linq.Enumerable.WhereSelectListIterator?System.Linq.Enumerable.WhereListIterator&System.Linq.Enumerable.WhereSelectListIterator之間的區別是什麼?

一個區別我甲肝注意到的是類型WhereListIterator反映集合對象上的變化,但WhereSelectListIterator不

我將使其成爲如更加清晰。

我甲肝,我去找我的域對象從倉庫

var buckets = testRepository.GetBuckets(testIds); 

然後我選擇一個循環內從上述收集某些桶的情景

var bucketsForTest = buckets.Where(bucket => bucket.TestID == test.testId); 

然後我改變所有的單個屬性LooserTrafficDisributor對象的方法內的桶對象。

ITrafficDistributor distributor = new LooserTrafficDisributor(bucketsForTest); 

IEnumerable<Bucket> updatedBuckets = distributor.Distribute(test.AutoDecision); 

LooserTrafficDisributor

public LooserTrafficDisributor(IEnumerable<Bucket> allBuckets) 
    { 
     this.allBuckets = allBuckets; 
    } 

內LooserTrafficDistributor的分配方法的構造看起來像這樣

private IEnumerable<Bucket> DistributeTraffic(bool autoDecision) 
{ 
    // allBuckets is class variable in LooserTrafficDistributor object which is set through constructor shown above . 
    // Omitted other details 

       allBuckets.Where(bucket=> bucket.IsControl == false).ToList() 
        .ForEach(bucket => bucket.TrafficPercentage += 10)); 
return allBuckets 
} 

這之後我看到了IEnumerable updatedBuckets集合內的反射變化。

但如果我這樣做,即不是從倉庫取桶收集的做了選擇&然後更新以類似的方式將所有對象鬥如下

var bucketsForTest = testRows.Where(testrow => testrow.url == url.url).Select(currRow => new Bucket 
    { 
       TestID = currRow.TestId, 
        BucketID = currRow.BucketId, 
        BucketName = currRow.c_bucket_name, 
        TrafficPercentage = Convert.ToInt32(currRow.i_bucket_percentage), 
        IsControl = currRow.b_is_control, 
        IsEnabled = currRow.b_enabled, 
        UpdatedAdminId = currRow.i_updated_admin_id, 
        LogAsSection = currRow.i_log_as_section 
      }) ; 

    ITrafficDistributor distributor = new LooserTrafficDisributor(bucketsForTest); 

    IEnumerable<Bucket> updatedBuckets = distributor.Distribute(test.AutoDecision, strategy.GetStatisticallySignificantLoosingBucketIds()); 

我不能什麼變化反映了IEnumerable內updatedBuckets集合。 Infact我在DistributeTraffic方法中調試,即使在每次循環後都沒有反映出變化。

回答

4

.Where()使您的項目的IEnumerable包含全部滿足where條件的所有元素。如果您在該結果集上運行.Select(),則會在select語句中獲得您創建的新元素的IEnumerable。所以對原始元素的更改將而不是反映在新元素上。

在您的示例中,您將爲原始列表中的每個存儲桶創建一個新的存儲桶對象,並將原始存儲桶中的內容複製到新存儲桶中。

+0

老兄你只有一半儀式在說我在我的例如。我創建了「一個新的Bucket對象,**將內容從原桶中複製到新的Bucket **。在我的第二部分中,我從testRows中選擇了」testrows「是一個不同類型的集合&Infact在末尾添加.TOList()可以解決問題 – Vipresh

+4

@vipresh你能否更注意自己的寫作?這很難理解。 – CodesInChaos

相關問題