2017-03-05 65 views
0

我有一個類:C#如何調用爲每個項目的方法在一個List <>

[DataContract] 
public class InventoryItem : NotifyPropertyChangeObject 
{ 
    private Guid _inventoryItemUid; 
    private string _description; 
    private bool _isActive; 

    [DataMember] 
    public Guid InventoryItemUid { 
     get { return _inventoryItemUid; } 
     set { ApplyPropertyChange<InventoryItem, Guid>(ref _inventoryItemUid, o => o.InventoryItemUid, value); } 
    } 
    [DataMember] 
    public string Description { 
     get { return _description; } 
     set { ApplyPropertyChange<InventoryItem, String>(ref _description, o => o.Description, value); } 
    } 
    [DataMember] 
    public bool IsActive { 
     get { return _isActive; } 
     set { ApplyPropertyChange<InventoryItem, Boolean>(ref _isActive, o => o.IsActive, value); } 
    } 

    public void CustomMethod() 
    { 
     // here some code.... 
    } 
} 

在我的應用程序代碼中,我得到一個List<InventoryItem>

List<Entities.InventoryItem> items = new List<Entities.InventoryItem>(); 

var newItem = new Entities.InventoryItem(); 

using (Logistics.Data.Warehouse svc = new Data.Warehouse()) 
{ 
    items = svc.GetInventoryItems().ToList(); 
} 

我需要調用每一個項目List<InventoryItem>方法CustomMethod()

在性能方面做什麼最好的方法是什麼?

我知道我可以做一個foreach,但如果我得到5000行,那麼也許foreach是不好的表現。其實這CustomMethod()就像一個初始化代碼的東西。

+0

有沒有辦法繞過它,你需要一個循環 –

+0

但是,如果你仍然需要調用每一行的方法,如果你有5行或5000是如何重要?也許你可以解釋這個方法是什麼(除非它真的對每一行都做了些什麼,然後就沒有辦法)。 – master2080

+0

如果需要在每個項目上調用它,爲什麼不把它放在構造函數中呢? – tomassino

回答

0

如果您的列表是一個巨大的列表,你可以用20個項目劃分它在團體和做你的行動並行在他們每個人:

private void CustomVoid(string s) 
{ 

} 

和:

List<string> items = new List<string>(); 
for (int i = 0; i <= items.Count/20; i++) 
{ 
     List<string> smallList = items.Skip(i * 20).Take(20).ToList(); 
     smallList.AsParallel().ForAll(sm => CustomVoid(sm)); 
} 

在評論下面建議忘記循環,只用這個:

items.AsParallel().ForAll(sm => CustomVoid(sm)); 

這可能會有更好的表現。

我希望它有幫助。

+1

爲什麼將它分成20個項目而不是讓PLINQ確定如何優化它? –

+1

這會比只是items.AsParallel – Slai

+0

你的意思是:'Parallel.ForEach( 項目, 新的ParallelOptions {MaxDegreeOfParallelism =?},'你的建議是什麼?** 20 **是他必須的樣本編號根據他的情況選擇它@Peter Bons。 –

相關問題