중복 제거 방법 HashSet

Unity3D/C# 2015. 2. 24. 19:18
반응형

HashSet, HashTable 차이점 : http://darksilber.tistory.com/entry/HashMap-HashTable-HashSet-%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90-%EC%99%B8-%EA%B8%B0%ED%83%80

HashSet은 .NET Framework 3.5에 처음 추가된 Generic Class로 어셈블리는 System.Core.dll이고, 
Namespace는 System.Collections.Generic 입니다. 

(주의 .NET Framework 3.5가 설치되어 있지 않으면 당연히 위의 클래스를 사용할 수 없습니다.)
 
Hash 특성상 내부의 hash function으로 현재 collection 안에 들어있는 값을 찾는데 걸리는 시간이 적고, Set 특성상 같은 내용을 중복으로 담고 있지 않습니다.
(그러나 Add 메소드는 상대적으로 다른 Collection보다 느릴 수 있기 때문에, 아주 긴 파일(수 MB가 넘는 파일)에는 적합하지 
않을 수 도 있습니다.)
해당 내용은 아래와 같이 구현할 수 있습니다.

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;

namespace HashSetTest
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet set = new HashSet();

            using (TextReader reader = File.OpenText("test.txt"))
            {
                string line = reader.ReadLine();
                while (string.IsNullOrEmpty(line) == false)
                {
                    set.Add(line);
                    line = reader.ReadLine();
                }
            }

            foreach (string setItem in set)
            {
                Console.WriteLine(setItem);
            }
        }
    }
}
반응형
: