Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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 55 views
2 answers 131 views
1 answer 126 views
2 answers 150 views
...