更新对象列表属性的更好方法

时间:2018-04-12 19:58:27

标签: c# .net

我正在开发一个功能,我有一个对象列表。我需要获得一个对象属性的最终列表,其中一个对象属性已被修改。目前大约需要58分钟,但我需要在6分钟内完成此过程。我正在寻找成员的一些反馈,看看如何在6分钟内完善此代码。感谢任何输入。

// Start with a List of ListItems with 350K records 
// ListItem(id, Name, Category, State, SortId)

List<ListItem> resultlist = new List<ListItem>();
List<ListItem> filterList = new List<ListItem>();

// List has 350K recrods
foreach (ListItem item in processList)
{
    // filter the lsit for particular id. 
    var filterList = processList.Where(p => p.Id == item.Id);

    // Additional logic to update the Category of the ListItem
    String AssignedCategory = GetFinalCategory() 

  // update all the filterList with AssignedCategory
    foreach (var item2Add in filterList)
    {
        item2Add.Category = AssignedCategory
        resultlist.Add(item2Add);
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用并行任务库使其具有多线程并加快处理速度。

    Parallel.ForEach(resultList, (currentResult) =>{
       // Property changing logic here.
    });

You can find more information here

答案 1 :(得分:1)

在你的第一个foreach中,你循环遍历processList中的每个项目。 然后你得到的foreach项目将过滤掉与当前项目匹配的所有项目 针对processList的item id。这将在processList中的foreach项中完成,这意味着 如果你有多个具有相同身份证明的项目,那么你将有更多的工作。

您应该做的是循环遍历主foreach中processList中的每个唯一ID 这将减少迭代并消除冗余工作。

var resultlist = new List<ListItem>();
var filterList = new List<ListItem>();

foreach (var id in processList.Select(i=> i.Id).Distinct())
{
    // filter the list for particular id. 
    var filterList = processList.Where(p => p.Id == id);

    // additional logic to update the Category of the ListItem
    var assignedCategory = GetFinalCategory() 

    // update all the filterList with assignedCategory
    foreach (var item2Add in filterList)
    {
        item2Add.Category = assignedCategory
        resultlist.Add(item2Add);
    }
}