C#의 StringCollection에서 지정한 개체의 인덱스를 검색하려면 IndexOf() 메서드를 사용합니다. 이 메서드는 해당 문자열이 컬렉션 내에서 처음으로 나타나는 위치의 인덱스를 반환하며, 존재하지 않을 경우 -1을 반환합니다.
예제 1: IndexOf()로 특정 요소의 인덱스 구하기
다음 예제에서는 StringCollection에 여러 문자열을 추가하고, Insert()로 새 요소를 삽입한 뒤, IndexOf()를 사용해 특정 개체의 인덱스를 확인합니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol = new StringCollection();
strCol.Add("Accessories");
strCol.Add("Books");
strCol.Add("Electronics");
strCol.Add("Books");
Console.WriteLine("StringCollection 요소...");
foreach (string res in strCol) {
Console.WriteLine(res);
}
// 인덱스 2 위치에 "Headphone" 삽입
strCol.Insert(2, "Headphone");
Console.WriteLine("StringCollection 요소... 업데이트됨");
foreach (string res in strCol) {
Console.WriteLine(res);
}
Console.WriteLine("특정 개체 Electronics의 인덱스? = " + strCol.IndexOf("Electronics"));
}
}출력 결과
StringCollection 요소... Accessories Books Electronics Books StringCollection 요소... 업데이트됨 Accessories Books Headphone Electronics Books 특정 개체 Electronics의 인덱스? = 3
위 결과에서 볼 수 있듯이, 인덱스 2에 "Headphone"이 삽입되면서 기존 "Electronics"의 인덱스가 2에서 3으로 변경되었습니다. 이처럼 IndexOf()는 항상 현재 컬렉션 상태를 기준으로 인덱스를 반환합니다.
예제 2: 배열 추가 후 Contains()와 함께 사용하기
다음 예제에서는 AddRange()로 배열 전체를 StringCollection에 추가하고, Contains()로 특정 문자열의 존재 여부를 확인한 후 IndexOf()로 인덱스를 검색합니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("배열 요소...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("지정한 문자열이 StringCollection에 있는가? = " + stringCol.Contains("800"));
Console.WriteLine("총 요소 수 = " + stringCol.Count);
Console.WriteLine("StringCollection 순회:");
StringEnumerator myenum = stringCol.GetEnumerator();
while (myenum.MoveNext())
Console.WriteLine(myenum.Current);
Console.WriteLine("특정 개체 500의 인덱스? = " + stringCol.IndexOf("500"));
Console.WriteLine("특정 개체 1000의 인덱스? = " + stringCol.IndexOf("1000"));
}
}출력 결과
배열 요소... 100 200 300 400 500 지정한 문자열이 StringCollection에 있는가? = False 총 요소 수 = 5 StringCollection 순회: 100 200 300 400 500 특정 개체 500의 인덱스? = 4 특정 개체 1000의 인덱스? = -1
핵심 정리
- IndexOf(string): 지정한 문자열이 처음 나타나는 인덱스를 반환하며, 없으면 -1을 반환합니다.
- Contains(string): 해당 문자열의 존재 여부를 true/false로 확인할 때 유용합니다.
- Insert(index, value): 요소를 삽입하면 이후 요소들의 인덱스가 자동으로 조정됩니다.
- AddRange(array): 배열의 모든 요소를 한 번에 컬렉션에 추가할 수 있습니다.
컬렉션 내 중복 값이 있을 경우 IndexOf()는 가장 앞쪽(첫 번째) 인덱스만 반환한다는 점도 기억해 두면 좋습니다.