C# | 목록에 지정된 요소가 포함되어 있는지 확인하는 방법
List.Contains(T) 메서드 요소가 목록에 있는지 여부를 확인하는 데 사용됩니다. 목록의 속성:
- 배열과는 다릅니다. 목록은 동적으로 크기를 조정할 수 있지만 배열은 그렇지 않습니다.
- 목록 클래스는 참조 유형에 대한 유효한 값으로 null을 허용할 수 있으며 중복 요소도 허용합니다.
- 만약 세다 다음과 같아진다 용량 그러면 내부 배열을 재할당하여 목록의 용량이 자동으로 늘어납니다. 새 요소를 추가하기 전에 기존 요소가 새 배열에 복사됩니다.
통사론:
public bool Contains (T item);
여기, 안건 목록에서 찾을 개체입니다. 참조 유형의 경우 값은 null일 수 있습니다. 반환 값: 이 메서드는 반환 진실 항목이 목록에서 발견되면 그렇지 않으면 반환됩니다. 거짓 . 아래 프로그램은 List.Contains(T) 메서드: 예시 1:
CSharp
// C# Program to check whether the> // element is present in the List> // or not> using> System;> using> System.Collections;> using> System.Collections.Generic;> class> Geeks {> > // Main Method> > public> static> void> Main(String[] args)> > {> > // Creating an List of Integers> > List <> int> >첫 번째 목록 => new> List <> int> >();> > // Adding elements to List> > firstlist.Add(1);> > firstlist.Add(2);> > firstlist.Add(3);> > firstlist.Add(4);> > firstlist.Add(5);> > firstlist.Add(6);> > firstlist.Add(7);> > // Checking whether 4 is present> > // in List or not> > Console.Write(firstlist.Contains(4));> > }> }> |
산출:
True
예시 2:
CSharp
// C# Program to check whether the> // element is present in the List> // or not> using> System;> using> System.Collections;> using> System.Collections.Generic;> class> Geeks {> > // Main Method> > public> static> void> Main(String[] args)> > {> > // Creating an List of String> > List firstlist => new> List();> > // Adding elements to List> > firstlist.Add(> 'Geeks'> );> > firstlist.Add(> 'For'> );> > firstlist.Add(> 'Geeks'> );> > firstlist.Add(> 'GFG'> );> > firstlist.Add(> 'C#'> );> > firstlist.Add(> 'Tutorials'> );> > firstlist.Add(> 'techcodeview.com'> );> > // Checking whether Java is present> > // in List or not> > Console.Write(firstlist.Contains(> 'Java'> ));> > }> }> |
산출:
False
시간 복잡도: Contains 메서드의 경우 O(n)
보조 공간: O(n) 여기서 n은 목록의 크기입니다.
참조: