programing

사전에서 키 목록을 가져오려면 어떻게 해야 합니까?

newnotes 2023. 4. 10. 22:11
반응형

사전에서 키 목록을 가져오려면 어떻게 해야 합니까?

나는 사전의 값이 아닌 키만 원한다.

아직 암호를 못 알아냈어요다른 어레이를 사용하면 remove도 사용하기 때문에 작업이 너무 많이 소요됩니다.

사전에서 키 목록을 가져오려면 어떻게 해야 합니까?

List<string> keyList = new List<string>(this.yourDictionary.Keys);

넌 그냥 볼 수 있을 거야.Keys:

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    foreach (string key in data.Keys)
    {
        Console.WriteLine(key);
    }

의 갱신을 실시.NET 3.5 이상

모든 키 목록을 가져오려면:

using System.Linq;

List<String> myKeys = myDict.Keys.ToList();

를 사용하여 문제가 발생했을 경우System.Linq다음을 참조해 주세요.

마크 그라벨의 답변이 효과가 있을 겁니다. myDictionary.Keys구현된 개체를 반환합니다.ICollection<TKey>,IEnumerable<TKey>그리고 그 외 다른 상대도 마찬가지입니다.

이 값에 액세스 할 계획이라면 사전을 다음과 같이 루프할 수 있습니다(수정된 예).

Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);

foreach (KeyValuePair<string, int> item in data)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

나는 이 모든 복잡한 대답들을 믿을 수 없다.키가 type: string(또는 게으른 개발자인 경우 'var' 사용):

List<string> listOfKeys = theCollection.Keys.ToList();

질문은 조금 이해하기 어렵지만 키를 반복하면서 사전에서 요소를 제거하려고 하는 것이 문제인 것 같습니다.이 경우 두 번째 어레이를 사용할 수밖에 없다고 생각합니다.

ArrayList lList = new ArrayList(lDict.Keys);
foreach (object lKey in lList)
{
  if (<your condition here>)
  {
    lDict.Remove(lKey);
  }
}

Array List가 아닌 범용 목록과 사전을 사용할 수 있다면 사용할 수 있지만 위의 내용은 그대로 사용할 수 있습니다.

또는 다음과 같이 합니다.

List< KeyValuePair< string, int > > theList =
    new List< KeyValuePair< string,int > >(this.yourDictionary);

for ( int i = 0; i < theList.Count; i++)
{ 
  // the key
  Console.WriteLine(theList[i].Key);
}

하이브리드 사전의 경우 다음을 사용합니다.

List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());

사전에서 키와 값을 얻기 위해 자주 사용하였습니다. (VB)네트워크)

 For Each kv As KeyValuePair(Of String, Integer) In layerList

 Next

(레이어 리스트는 사전 타입(String, Integer)입니다).

언급URL : https://stackoverflow.com/questions/1276763/how-do-i-get-the-list-of-keys-in-a-dictionary

반응형