development

인스턴스화에서 C # 사전에 값을 삽입하는 방법은 무엇입니까?

big-blog 2020. 6. 16. 07:51
반응형

인스턴스화에서 C # 사전에 값을 삽입하는 방법은 무엇입니까?


C # Dictionary를 만들 때 값을 삽입 할 수있는 방법이 있는지 아는 사람이 있습니까? dict.Add(int, "string")더 효율적인 것이 있다면 각 항목마다 할 수는 있지만 원하지는 않습니다 .

Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};

이를 수행하는 방법에 대한 전체 페이지가 있습니다.

http://msdn.microsoft.com/en-us/library/bb531208.aspx

예:

다음 코드 예제에서 a Dictionary<TKey, TValue>다음 유형의 인스턴스로 초기화됩니다 StudentName.

var students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};

Dictionary<int, string> dictionary = new Dictionary<int, string> { 
   { 0, "string" }, 
   { 1, "string2" }, 
   { 2, "string3" } };

당신은 거의 그곳에있었습니다.

var dict = new Dictionary<int, string>()
{ {0, "string"}, {1,"string2"},{2,"string3"}};

Lambda 식을 사용하여 다른 IEnumerable 객체에서 Key Value 쌍을 삽입 할 수도 있습니다. 키와 값은 원하는 모든 유형이 될 수 있습니다.

Dictionary<int, string> newDictionary = 
                 SomeList.ToDictionary(k => k.ID, v => v.Name);

.NET의 모든 곳에서 IEnumerable 객체를 사용하기 때문에 훨씬 간단합니다.

희망이 도움이됩니다 !!!

약간.


사전을 인스턴스화하고 다음과 같이 사전에 항목을 추가 할 수 있습니다.

var dictionary = new Dictionary<int, string>
    {
        {0, "string"},
        {1, "string2"},
        {2, "string3"}
    };

C # 6부터 알 수 있으므로 이제 다음과 같이 초기화 할 수 있습니다

var students = new Dictionary<int, StudentName>()
{
    [111] = new StudentName {FirstName="Sachin", LastName="Karnik", ID=211},
    [112] = new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317},
    [113] = new StudentName {FirstName="Andy", LastName="Ruth", ID=198}
};

훨씬 더 깨끗한 :)


그것이 완벽하게 작동하기를 바랍니다.

Dictionary<string, double> D =new Dictionary<string, double>(); D.Add("String", 17.00);


이것은 일반적으로 권장되지 않지만 위기가 불확실한 경우 사용할 수 있습니다

Dictionary<string, object> jsonMock = new Dictionary<string, object>() { { "object a", objA }, { "object b", objB } };

// example of unserializing
ClassForObjectA anotherObjA = null;
if(jsonMock.Contains("object a")) {
    anotherObjA = (ClassForObjA)jsonMock["object a"];
}

참고 URL : https://stackoverflow.com/questions/1039610/how-to-insert-values-into-c-sharp-dictionary-on-instantiation

반응형