C #에서 2 차원 목록이 가능합니까?
다차원 목록을 설정하고 싶습니다. 참고로 재생 목록 분석기 작업 중입니다.
내 프로그램이 표준 목록에 저장하는 파일 / 파일 목록이 있습니다. 각 목록 항목의 파일에서 한 줄.
그런 다음 정규식으로 목록을 분석하여 특정 줄을 찾습니다. 라인의 일부 데이터 / 결과는 새로운 다차원 목록에 넣어야 합니다. 얼마나 많은 결과 / 데이터로 끝날지 모르기 때문에 다차원 배열을 사용할 수 없습니다.
삽입하려는 데이터는 다음과 같습니다.
명부 ( [0] => 목록 ( [0] => 트랙 ID [1] => 이름 [2] => 아티스트 [3] => 앨범 [4] => 플레이 횟수 [5] => 스킵 카운트 ) [1] => 목록 ( 등등....
실제 예 :
명부 ( [0] => 목록 ( [0] => 2349 [1] => 삶의 황금기 [2] => 멍청한 펑크 [3] => 결국 인간 [4] => 3 [5] => 2 ) [1] => 목록 (
예, mlist [0] [0]은 노래 1에서 TrackID를, 노래 2에서 mlist [1] [0]을 가져옵니다.
하지만 다차원 목록을 만드는 데 큰 문제가 있습니다. 지금까지 나는
List<List<string>> matrix = new List<List<string>>();
그러나 나는 정말로 더 많은 진전이 없었습니다 :(
다음과 같이 작성할 위치 를 확실히 사용할 수 있습니다 List<List<string>>
.
List<string> track = new List<string>();
track.Add("2349");
track.Add("The Prime Time of Your Life");
// etc
matrix.Add(track);
하지만 트랙 ID, 이름, 아티스트, 앨범, 재생 횟수 및 건너 뛰기 횟수 속성을 사용하여 트랙을 나타내는 자체 클래스를 만드는 대신 왜 그렇게할까요? 그런 다음 List<Track>
.
로 존 소총은 당신이 함께 할 수있는 언급 List<Track>
대신. Track 클래스는 다음과 같습니다.
public class Track {
public int TrackID { get; set; }
public string Name { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public int PlayCount { get; set; }
public int SkipCount { get; set; }
}
트랙 목록을 만들려면 다음과 같이 List<Track>
하십시오.
var trackList = new List<Track>();
트랙 추가는 다음과 같이 간단 할 수 있습니다.
trackList.add( new Track {
TrackID = 1234,
Name = "I'm Gonna Be (500 Miles)",
Artist = "The Proclaimers",
Album = "Finest",
PlayCount = 10,
SkipCount = 1
});
인덱싱 연산자를 사용하여 트랙에 액세스 할 수 있습니다.
Track firstTrack = trackList[0];
도움이 되었기를 바랍니다.
이것이 내가 찾은 가장 쉬운 방법입니다.
List<List<String>> matrix= new List<List<String>>(); //Creates new nested List
matrix.Add(new List<String>()); //Adds new sub List
matrix[0].Add("2349"); //Add values to the sub List at index 0
matrix[0].Add("The Prime of Your Life");
matrix[0].Add("Daft Punk");
matrix[0].Add("Human After All");
matrix[0].Add("3");
matrix[0].Add("2");
값을 검색하는 것이 훨씬 더 쉽습니다.
string title = matrix[0][1]; //Retrieve value at index 1 from sub List at index 0
내가 사용한 또 다른 작업은 ...
List<int []> itemIDs = new List<int[]>();
itemIDs.Add( new int[2] { 101, 202 } );
내가 작업중인 라이브러리는 매우 형식적인 클래스 구조를 가지고 있으며 두 개의 '관련'int를 기록 할 수있는 특권을 위해 효과적으로 거기에 추가 항목을 원하지 않았습니다.
프로그래머가 2 항목 배열 만 입력하는 데 의존하지만 일반적인 항목이 아니기 때문에 작동한다고 생각합니다.
이 방법으로도 할 수 있습니다.
List<List<Object>> Parent=new List<List<Object>>();
List<Object> Child=new List<Object>();
child.Add(2349);
child.Add("Daft Punk");
child.Add("Human");
.
.
Parent.Add(child);
다른 항목 (자식)이 필요하면 자식의 새 인스턴스를 만들고
Child=new List<Object>();
child.Add(2323);
child.Add("asds");
child.Add("jshds");
.
.
Parent.Add(child);
Here is how to make a 2 dimensional list
// Generating lists in a loop.
List<List<string>> biglist = new List<List<string>>();
for(int i = 1; i <= 10; i++)
{
List<string> list1 = new List<string>();
biglist.Add(list1);
}
// Populating the lists
for (int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
biglist[i].Add((i).ToString() + " " + j.ToString());
}
}
textbox1.Text = biglist[5][9] + "\n";
Be aware of the danger of accessing a location that is not populated.
I used:
List<List<String>> List1 = new List<List<String>>
var List<int> = new List<int>();
List.add("Test");
List.add("Test2");
List1.add(List);
var List<int> = new List<int>();
List.add("Test3");
List1.add(List);
that equals:
List1
(
[0] => List2 // List1[0][x]
(
[0] => Test // List[0][0] etc.
[1] => Test2
)
[1] => List2
(
[0] => Test3
You can also use DataTable - you can define then the number of columns and their types and then add rows http://www.dotnetperls.com/datatable
Here's a little something that I made a while ago for a game engine I was working on. It was used as a local object variable holder. Basically, you use it as a normal list, but it holds the value at the position of what ever the string name is(or ID). A bit of modification, and you will have your 2D list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GameEngineInterpreter
{
public class VariableList<T>
{
private List<string> list1;
private List<T> list2;
/// <summary>
/// Initialize a new Variable List
/// </summary>
public VariableList()
{
list1 = new List<string>();
list2 = new List<T>();
}
/// <summary>
/// Set the value of a variable. If the variable does not exist, then it is created
/// </summary>
/// <param name="variable">Name or ID of the variable</param>
/// <param name="value">The value of the variable</param>
public void Set(string variable, T value)
{
if (!list1.Contains(variable))
{
list1.Add(variable);
list2.Add(value);
}
else
{
list2[list1.IndexOf(variable)] = value;
}
}
/// <summary>
/// Remove the variable if it exists
/// </summary>
/// <param name="variable">Name or ID of the variable</param>
public void Remove(string variable)
{
if (list1.Contains(variable))
{
list2.RemoveAt(list1.IndexOf(variable));
list1.RemoveAt(list1.IndexOf(variable));
}
}
/// <summary>
/// Clears the variable list
/// </summary>
public void Clear()
{
list1.Clear();
list2.Clear();
}
/// <summary>
/// Get the value of the variable if it exists
/// </summary>
/// <param name="variable">Name or ID of the variable</param>
/// <returns>Value</returns>
public T Get(string variable)
{
if (list1.Contains(variable))
{
return (list2[list1.IndexOf(variable)]);
}
else
{
return default(T);
}
}
/// <summary>
/// Get a string list of all the variables
/// </summary>
/// <returns>List string</string></returns>
public List<string> GetList()
{
return (list1);
}
}
}
참고URL : https://stackoverflow.com/questions/665299/are-2-dimensional-lists-possible-in-c
'IT박스' 카테고리의 다른 글
소스 코드를 왼쪽으로 들여 쓰는 Eclipse 키보드 단축키? (0) | 2020.09.20 |
---|---|
Mac에서 ARC를 사용하여 respondsToSelector를 사용할 수 없음 (0) | 2020.09.20 |
VS 2012는 사용자 지정 바인딩 호스트와 함께 IIS를 사용하는 프로젝트를로드 할 수 없습니다-IIS Express를 사용하고 있다고 생각합니다. (0) | 2020.09.20 |
Express 4 및 Express 생성기의 / bin / www에서 socket.io 사용 (0) | 2020.09.20 |
컴포넌트 내에서 요소를 가져 오는 VueJ (0) | 2020.09.20 |