IT

HashSet의 차이점은 무엇입니까

lottoking 2020. 6. 12. 08:38
반응형

HashSet의 차이점은 무엇입니까 와 목록?


.NET HashSet<T>의 차이점을 설명 할 수 있습니까 List<T>?

어쩌면 어떤 경우에 HashSet<T>선호 해야하는지 예를 통해 설명 할 수 List<T>있습니까?


리스트와 달리 <> ...

  1. HashSet은 중복 멤버가없는 목록입니다.

  2. HashSet은 고유 한 항목 만 포함하도록 제한되므로 내부 구조는 검색에 최적화되어 (목록과 비교) 훨씬 빠릅니다.

  3. HashSet에 추가하면 부울이 반환됩니다. Set에 이미 존재하여 추가에 실패하면 false

  4. Set : Union / Intersection / IsSubsetOf 등에 대해 수학적인 세트 연산을 수행 할 수 있습니다.

  5. HashSet은 IList 만 구현하지 않습니다. ICollection

  6. HashSet에는 인덱스를 사용할 수 없으며 열거 자만 사용할 수 있습니다.

HashSet을 사용하는 주된 이유는 Set 작업 수행에 관심이있는 것입니다.

주어진 2 세트 : hashSet1 및 hashSet2

 //returns a list of distinct items in both sets
 HashSet set3 = set1.Union( set2 );

LINQ를 사용하는 동등한 작업과 비교하여 날아갑니다. 쓰는 것이 더 깔끔합니다!


A HashSet<T>O(1)봉쇄 를 찾아 보기 위해 고안된 클래스입니다 (즉,이 컬렉션에 특정 개체가 포함되어 있고 답을 빨리 알려주세요).

A List<T>O(1)동적으로 성장할 수있는 것 (동적 배열을 생각할 수있는 것)보다 무작위로 액세스 할 수있는 모음을 제공하도록 설계된 클래스입니다 . 당신의 봉쇄를 테스트 할 수 있습니다 O(n)(목록이 정렬되어 있지 않으면, 다음에 이진 검색 할 수있는 시간 O(log n)시간).

어쩌면 어떤 경우에 HashSet<T>선호 해야하는지에 대한 예를 들어 설명 할 수 있습니다.List<T>

당신의 봉쇄를 테스트 할 때 O(1).


더 정확하게 설명하기 위해 예제를 통해 설명하겠습니다.

다음 예제와 같이 HashSet을 사용할 수 없습니다.

HashSet<string> hashSet1 = new HashSet<string>(){"1","2","3"};
for (int i = 0; i < hashSet1.Count; i++)
    Console.WriteLine(hashSet1[i]);

hashSet1[i] 오류가 발생합니다.

'System.Collections.Generic.HashSet'형식의 식에 []를 사용하여 인덱싱을 적용 할 수 없습니다.

foreach 문을 사용할 수 있습니다.

foreach (var item in hashSet1)
    Console.WriteLine(item);


List를 사용하면이 작업을 수행 할 수 있고 HashSet에 항목을 추가하는 동안 항목을 포함하는지 여부를 확인할 수있는 동안 중복 된 항목을 HashSet에 추가 할 수 없습니다.

HashSet<string> hashSet1 = new HashSet<string>(){"1","2","3"};
if (hashSet1.Add("1"))
   Console.WriteLine("'1' is successfully added to hashSet1!");
else
   Console.WriteLine("'1' could not be added to hashSet1, because it contains '1'");

HashSet의이 같은 몇 가지 유용한 기능이있다 IntersectWith, UnionWith, IsProperSubsetOf, ExceptWith, SymmetricExceptWith

IsProperSubsetOf:

HashSet<string> hashSet1 = new HashSet<string>() { "1", "2", "3", "4" };
HashSet<string> hashSet2 = new HashSet<string>() { "2", "4", "6", "8" };
HashSet<string> hashSet3 = new HashSet<string>() { "1", "2", "3", "4", "5" };
if (hashSet1.IsProperSubsetOf(hashSet3))
    Console.WriteLine("hashSet3 contains all elements of hashSet1.");
if (!hashSet1.IsProperSubsetOf(hashSet2))
    Console.WriteLine("hashSet2 does not contains all elements of hashSet1.");

UnionWith:

HashSet<string> hashSet1 = new HashSet<string>() { "3", "4" };
HashSet<string> hashSet2 = new HashSet<string>() { "2", "4", "6", "8" };
hashSet1.UnionWith(hashSet2); //hashSet1 -> 3, 2, 4, 6, 8

IntersectWith:

HashSet<string> hashSet1 = new HashSet<string>() { "3", "4", "8" };
HashSet<string> hashSet2 = new HashSet<string>() { "2", "4", "6", "8" }
hashSet1.IntersectWith(hashSet2);//hashSet1 -> 4, 8

ExceptWith :

 HashSet<string> hashSet1 = new HashSet<string>() { "1", "2", "3", "5", "6" };
 HashSet<string> hashSet2 = new HashSet<string>() { "1", "2", "3", "4" };
 hashSet1.ExceptWith(hashSet2);//hashSet1 -> 5, 6

SymmetricExceptWith :

 HashSet<string> hashSet1 = new HashSet<string>() { "1", "2", "3", "5", "6" };
 HashSet<string> hashSet2 = new HashSet<string>() { "1", "2", "3", "4" };
 hashSet1.SymmetricExceptWith(hashSet2);//hashSet1 -> 4, 5, 6

그건 그렇고, 순서는 HashSets에서 유지되지 않습니다. 이 예에서는 마지막에 "2"요소를 추가했지만 두 번째 순서입니다.

HashSet<string> hashSet1 = new HashSet<string>() { "3", "4", "8" };
hashSet1.Add("1");    // 3, 4, 8, 1
hashSet1.Remove("4"); // 3, 8, 1
hashSet1.Add("2");    // 3, 2 ,8, 1

다음 List<T>을 원할 때를 사용하십시오 .

  • 항목 모음을 특정 순서로 저장하십시오.

If you know the index of the item you want (rather than the value of the item itself) retrieval is O(1). If you don't know the index, finding the item takes more time, O(n) for an unsorted collection.

Use a Hashset<T> when you want to:

  • Quickly find out if a certain object is contained in a collection.

If you know the name of the thing you want to find, Lookup is O(1) (that's the 'Hash' part). It doesn't maintain an ordering like the List<T> does and you can't store duplicates (adding a duplicate has no effect, that's the 'Set' part).

An example of when to use a Hashset<T> would be if you want to find out if a word played in a game of Scrabble is a valid word in English (or other language). Even better would be if you wanted to build a web service to be used by all instances of an online version of such a game.

A List<T> would be a good data structure for creating the scoreboard to track player scores.


List is an ordered list. It is

  • accessed by an integer index
  • can contain duplicates
  • has a predictable order

HashSet is a set. It:

  • Can block duplicate items (see Add(T))
  • Does not guarantee the order of the items within the set
  • Has operations you would expect on a set, e.g., IntersectWith, IsProperSubsetOf, UnionWith.

List is more appropriate when you want to access you collection as though it were like an array to which you could append, insert and remove items. HashSet is a better choice if you want to treat your collection like a "bag" of items in which order is not important or when you want to compare it with other sets using the operations such as IntersectWith or UnionWith.


List is not necessarily unique, while hashset is, for one.


A List is an ordered collection of objects of Type T that unlike an array you can add and remove entries.

You would use a list where you want to reference the members in the order you stored them and you are accessing them by an position rather than the item itself.

A HashSet is like a dictionary that the item itself is the key as well as the value, the ordering is not guaranteed.

You would use a HashSet where you want to check that an object is in the collection


If you decide to apply these data structures to actual usage in data-driven development, a HashSet is VERY helpful in testing replication against data adapter sources, for data cleansing and migration.

Also, if using the DataAnnotations Class, one can implement Key logic on class properties and effectively control a Natural Index (clustered or not) with a HashSet, where this would be very difficult in a List implementation.

A strong option for using a list is to implement generics for multiple mediums on a View Model, such as sending a list of classes to a MVC View for a DropDownList Helper, and also for sending as a JSON construct via WebApi. The list allows typical class collection logic, and keeps flexibility for a more "Interface" like approach to computing a single view model to different mediums.

참고URL : https://stackoverflow.com/questions/6391738/what-is-the-difference-between-hashsett-and-listt

반응형