在运行时从对象列表中删除重复项时遇到问题。
我想从对象列表中删除重复项,然后设置基础对象的counter = counter + 1。
public class MyObject
{
MyObject(string name)
{
this.counter = 0;
this.name = name;
}
public string name;
public int counter;
}
List<MyObject> objects_list = new List<MyObject>();
objects_list.Add(new MyObject("john"));
objects_list.Add(new MyObject("anna"));
objects_list.Add(new MyObject("john"));
foreach (MyObject my_object in objects_list)
{
foreach (MyObject my_second_object in objects_list)
{
if (my_object.name == my_second_object.name)
{
my_object.counter = my_object.counter + 1;
objects_list.remove(my_second_object);
}
}
}
它返回一个错误,因为objects_list在运行时被修改。我该如何工作?
答案 0 :(得分:1)
借助 Linq GroupBy
,我们可以将重复项合并到单个组中并进行处理(即返回代表所有重复项的项目):
List<MyObject> objects_list = ...
objects_list = objects_list
.GroupBy(item => item.name)
.Select(group => { // given a group of duplicates we
var item = group.First(); // - take the 1st item
item.counter = group.Sum(g => g.counter); // - update its counter
return item; // - and return it instead of group
})
.ToList();
答案 1 :(得分:0)
另一个答案似乎是正确的,尽管我认为它将对整个列表进行两次扫描,这可能取决于您的要求,也可能不够。这是您一劳永逸的方法:
var dictionary = new Dictionary<string, MyObject>();
foreach(var obj in objects_list)
{
if(!dictionary.ContainsKey(obj.name)
{
dictionary[obj.name] = obj;
obj.counter++;
}
else
{
dictionary[obj.name].counter++;
}
}
然后字典。值将包含您的收藏