Remove duplicates from a List in C#

前端 未结 27 2167
广开言路
广开言路 2020-11-22 04:41

Anyone have a quick method for de-duplicating a generic List in C#?

27条回答
  •  萌比男神i
    2020-11-22 05:06

    There are many ways to solve - the duplicates issue in the List, below is one of them:

    List containerList = LoadContainer();//Assume it has duplicates
    List filteredList = new  List();
    foreach (var container in containerList)
    { 
      Container duplicateContainer = containerList.Find(delegate(Container checkContainer)
      { return (checkContainer.UniqueId == container.UniqueId); });
       //Assume 'UniqueId' is the property of the Container class on which u r making a search
    
        if(!containerList.Contains(duplicateContainer) //Add object when not found in the new class object
          {
            filteredList.Add(container);
           }
      }
    

    Cheers Ravi Ganesan

提交回复
热议问题