Removing duplicates from a list collection

后端 未结 4 1950
天命终不由人
天命终不由人 2021-01-21 02:37

Hope someone can help me. I am using c# and I am somewhat new to it. I am loading a text file into my app and splitting the data on \",\" I am reading part of string into a

相关标签:
4条回答
  • 2021-01-21 03:21

    A simple/dirty example follows:

    public List<string> RemoveDuplicates(List<string> listWithDups)
    {
       cleanList = new List<string>();
       foreach (string s in listWithDups)
       {
          if (!cleanList.Contains(s))
             cleanList.Add(s);
       }
       return cleanList;
    }
    

    As a warning: String.Split on very large strings can cause consume huge amounts of memory and cause exceptions.

    0 讨论(0)
  • 2021-01-21 03:25

    Here's an article with some examples and explanations in C#. Basically, you just keep track of the uniques, and check each element.

    Alex

    0 讨论(0)
  • 2021-01-21 03:32

    If you are targeting .NET 3.5, use the Distinct extension method:

    var deduplicated = list.Distinct();
    
    0 讨论(0)
  • 2021-01-21 03:37

    If you load the strings into a Set instead of into a List then duplicates are discarded automatically.

    0 讨论(0)
提交回复
热议问题