How to remove duplicates from a list in C#

2 Answers

0 votes
using System;
using System.Linq;
using System.Collections.Generic;
 
class Program
{
    static void Main() {
        var list = new List<int>() { 2, 4, 4, 9, 7, 3, 4, 6, 0, 3 };
         
        list = list.Distinct().ToList();
        
        Console.WriteLine(string.Join(" ", list));
    }
}
 
 
 
 
/*
run:
 
2 4 9 7 3 6 0
 
*/

 



answered Mar 19, 2023 by avibootz
0 votes
using System;
using System.Collections.Generic;
 
class Program
{
    public static List<string> RemoveDuplicates(List<string> list) {
        var result = new List<string>();
        var set = new HashSet<string>();
        
        for (int i = 0; i < list.Count; i++) {
            if (!set.Contains(list[i])) {
                result.Add(list[i]);
                set.Add(list[i]);
            }
        }
        return result;
    }
    
    static void Main()
    {
        var list = new List<string>() { "a", "b", "b", "a", "c", "b", "b", "c", "c", "d" };
        
        list = RemoveDuplicates(list);
        
        Console.WriteLine(string.Join(" ", list));
    }
}
 
 
 
 
/*
run:
 
a b c d
 
*/

 



answered Mar 19, 2023 by avibootz

Related questions

1 answer 80 views
2 answers 162 views
1 answer 157 views
2 answers 185 views
...