简体   繁体   English

如何基于C#中的对象属性从对象列表中删除重复项

[英]How to remove duplicates from object list based on that object property in c#

I've got a problem with removing duplicates at runtime from my list of object. 我在从对象列表中删除运行时的重复项时遇到问题。

I would like to remove duplicates from my list of object and then set counter=counter+1 of base object. 我想从我的对象列表中删除重复项,然后设置基础对象的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);
        }
    }
}

It return an error, because objects_list is modified at runtime. 它返回错误,因为objects_list在运行时被修改。 How can I get this working? 我该如何工作?

With a help of Linq GroupBy we can combine duplicates in a single group and process it (ie return an item which represents all the duplicates): 借助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();

The other answer seem to be correct, though I think it will do scan of the whole list twice, depending on your requirement this might or might not be good enough. 另一个答案似乎是正确的,尽管我认为它将对整个列表进行两次扫描,具体取决于您的要求,这可能不够好。 Here is how you can do it in one go: 这是您可以一次完成的方法:

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++;
  } 
}

Then dictionary.Values will contain your collection 然后字典。值将包含您的集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM