C#으로 나열

王林
풀어 주다: 2024-09-03 15:28:00
원래의
264명이 탐색했습니다.

C#의 목록은 데이터 저장 및 검색에 매우 중요한 역할을 합니다. 다음은 C#의 일반 목록( List )에 대한 몇 가지 중요한 사항입니다.

  • 목록< T > T는 목록의 개체 유형을 나타내는 강력한 형식의 개체 목록입니다.
  • 컬렉션 아래에 있습니다. 일반 네임스페이스.
  • 목록의 요소는 색인 번호를 통해 액세스할 수 있으며 목록의 색인은 0부터 시작합니다.
  • 목록 크기는 동적으로 조정될 수 있습니다.
  • 목록의 요소가 참조 유형인 경우 목록은 null 값도 허용할 수 있습니다.
  • 요소의 중복을 허용합니다.

구문:

List<T> list_name = new List<T>();
로그인 후 복사

설명: 위의 진술 List< T > 는 T 유형의 일반 목록입니다. 여기서 T는 int, string 등과 같은 모든 유형일 수 있습니다. 그리고 list_name은 사용자가 지정한 목록 이름입니다. 'new' 키워드를 사용하여 목록을 초기화합니다.

또한 IList의 도움으로 목록을 만들 수도 있습니다< T > 다음과 같은 인터페이스:

IList<T> list_name = new List<T>();
로그인 후 복사

C#에서 목록을 만드는 방법은 무엇입니까?

List를 사용하려면< T >, 먼저 프로그램에서 System.Collections.Generic 네임스페이스를 가져와야 합니다.

C#에서 목록을 만드는 방법은 다음과 같이 다양합니다.

  • List<를 사용하여 기본 용량으로 목록 만들기 T > 클래스 생성자.

예:

List<int> lstNum = new List<int>();
</p>
<p>위 명령문은 기본 용량을 갖는 정수 목록을 생성합니다. 사용자가 목록의 용량을 정의하지 않은 경우 항목이 목록에 추가될 때마다 목록의 크기가 늘어납니다.</p>
<p>ASP.NET 교육(9개 과정, 19개 프로젝트).NET 교육 프로그램(5개 과정, 19개 프로젝트)</p>
<ul>
<li>Add() 메소드를 사용하여 목록에 항목을 추가할 수 있습니다.</li>
</ul>
<p><strong>예:</strong></p>
<pre class="brush:php;toolbar:false">lstNum.Add(1);
lstNum.Add(2);
lstNum.Add(3);
로그인 후 복사

사용자가 정의한 용량으로 목록을 생성합니다.

예:

List<string> lstString = new List<string>(3);
로그인 후 복사

위 명령문은 용량이 3인 문자열 목록을 생성합니다. 목록에 3개 이상의 요소가 추가되면 용량이 자동으로 확장됩니다. 초기화하는 동안 목록에 항목을 추가할 수도 있습니다.

List<string> lstString = new List<string>(3)
{
"Neha",
"Shweta",
"Megha"
};
로그인 후 복사

다른 요소 컬렉션을 사용하여 목록을 만들 수도 있습니다.

예:

//string array of names
string[] names = {"Neha", "Shweta", "Megha"};
//creating list by using string array
List<string> lstNames = new List<string>(names);
로그인 후 복사

AddRange() 메소드를 사용하여 목록에 다른 요소 컬렉션을 추가할 수 있습니다.

예:

string[] names = {"Neha", "Shweta", "Megha"};
List<string> lstNames = new List<string>();
//adding elements of string array to list
lstNames.AddRange(names);
로그인 후 복사

예제를 포함한 C#의 목록 메서드

다음과 같이 List 클래스의 몇 가지 중요한 메소드에 대해 논의하겠습니다.

1. 추가( )

목록 끝에 개체를 추가하는 데 사용되는 메서드입니다. 참조 유형에 null 값을 추가할 수 있습니다.

예:

using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<int> lstNum = new List<int>(){1, 2, 3, 4};
//Adding 5 at the end of list
lstNum.Add(5);
foreach(int num in lstNum)
{
Console.WriteLine(num);
}
}
}
로그인 후 복사

출력:

C#으로 나열

2. 지우기()

이 방법은 목록에서 모든 요소를 ​​제거하는 데 사용됩니다.

예:

using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<int> lstNum = new List<int>(){1, 2, 3, 4, 5};
//removing all elements from the list
lstNum.Clear();
if(lstNum.Count > 0)
Console.WriteLine("List is not empty");
else
Console.WriteLine("List is empty");
}
}
로그인 후 복사

출력:

C#으로 나열

3. 삽입( Int32, T )

목록의 지정된 위치에 요소를 삽입하는 방법입니다. 두 개의 인수가 필요합니다. 첫 번째 인수는 요소를 삽입하려는 인덱스 번호이고 두 번째 인수는 요소 자체입니다.

예:

using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<string> lstCities = new List<string>(){"Mumbai", "Pune", "Bengaluru"};
//inserting element at third position
lstCities.Insert(2, "Chennai");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
}
}
로그인 후 복사

출력:

C#으로 나열

4. RemoveAt( Int32 )

목록에서 지정된 위치에 있는 항목을 제거하는 방법입니다.

예:

using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<string> lstCities = new List<string>() {"Mumbai","Pune","Bengaluru"};
Console.WriteLine("Initial list values");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
//removing element at second position
lstCities.RemoveAt(1);
Console.WriteLine("\nAfter removing element at second position");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
}
}
로그인 후 복사

출력:

C#으로 나열

5. 정렬()

이 방법은 기본 비교자를 사용하여 목록의 요소를 정렬하는 데 사용됩니다.

예:

using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<string> lstCities = new List<string>(){"Mumbai","Pune","Bengaluru"};
Console.WriteLine("Initial list values");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
//sorting elements in ascending order
lstCities.Sort();
Console.WriteLine("\nList after sorting in ascending order");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
//sorting elements in descending order by calling Reverse()
lstCities.Reverse();
Console.WriteLine("\nList after sorting in descending order");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
}
}
로그인 후 복사

출력:

C#으로 나열

위 프로그램에서는 먼저 Sort()를 사용하여 목록을 오름차순으로 정렬했습니다. 이제 목록을 내림차순으로 정렬하기 위해 정렬된 목록에서 Reverse() 메서드를 호출했습니다. Sort() 메서드를 사용하여 int, string 등의 형식 목록을 정렬할 수 있지만 사용자 지정 개체 형식의 목록을 정렬하려면 IComparable 인터페이스를 구현하거나 LINQ를 사용할 수도 있습니다. 아래 예와 같이 이 유형의 목록을 다른 방법으로 정렬할 수 있습니다.

예:

using System;
using System.Collections.Generic;
public class Student
{
public string Name { get; set; }
public int Marks { get; set; }
public Student(string name, int marks)
{
Name = name;
Marks = marks;
}
}
public class ListDemo
{
public static void Main()
{
List<Student> lstStudents = new List<Student>();
lstStudents.Add(new Student("Neha", 90));
lstStudents.Add(new Student("John", 75));
lstStudents.Add(new Student("Kate", 88));
lstStudents.Add(new Student("Arya", 70));
//sorting students in ascending order of their marks
lstStudents.Sort(CompareMarks);
foreach (Student student in lstStudents)
{
Console.WriteLine(student.Name + ": " + student.Marks);
}
}
public static int CompareMarks(Student student1, Student student2)
{
return student1.Marks.CompareTo(student2.Marks);
}
}
로그인 후 복사

출력:

C#으로 나열

결론

목록< T > 지정된 유형 요소의 일반 컬렉션입니다. 목록의 요소는 'for' 또는 'foreach' 루프를 사용하여 색인 번호를 통해 액세스할 수 있습니다. 목록에서는 추가, 삽입, 검색, 정렬 등 다양한 작업을 수행할 수 있습니다. 크기는 동적입니다.

위 내용은 C#으로 나열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!