[英]C# how to call method for every item in a 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
但是如果我得到5,000行,那么也许foreach
对性能不好。 实际上,此CustomMethod()
类似于初始化程序代码。
如果您的清单是一个庞大的清单,则可以将其分为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));
那可能会有更好的表现。
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.