Programming/C#

C# HashSet<T> 중복제거

JeongKyun 2021. 9. 26.
반응형

1. 수학과 같은 연산을 사용한다.

 

Ex ) 집합 형식을 사용할 사용

https://docs.microsoft.com/ko-kr/dotnet/api/system.collections.generic.hashset-1?view=netcore-3.1

 

HashSet 클래스 (System.Collections.Generic)

값 집합을 나타냅니다.Represents a set of values.

docs.microsoft.com

2. 중복제거할때 용이함

 

해당 아래의 예제는 HashSet의 예제로 작성했으며,

 

해당 경로에 있는 메모장의 Text에서 한줄 씩 ReadLine으로 받아 중복값을 제거하는 로직이다.

 

앞으로 HashSet은 중복제거할 때 자주 써먹자

 

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

namespace HashSet
{
	class Program
	{

		static void Main(string[] args)
		{
			HashSet<string> set = new HashSet<string>();

			using (System.IO.TextReader reader = 
				File.OpenText(
					Environment.GetFolderPath(
						Environment.SpecialFolder.Desktop) + @"\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);
			}

		}
	}
}

 

메모장 내용

===결과값===

결과 Console창

 

댓글

💲 많이 본 글