2017-02-22 3 views
1

Ich füge mehrere Werte Anwendungszustand wie:Get Application State Schlüsselnamen von Index

for(int i=0;i<MyList.Count;i++) 
    Application[MyList[i].Id.ToString()] = MyList[i].Value; 

Dann möchte ich die Werte für Ids entfernen, die abgelaufen sind (nicht in der aktuellen Favoritenliste). Ich möchte also alle Anwendungsstatuswerte durchlaufen und sie entfernen, wenn Id abgelaufen ist. so etwas wie dieses:

for(int i=0;i<Application.Count;i++) 
{ 
    int Id = int.Parse(Application[i].Key); // Here is what I want to do but I don't have access to key value 
    if(!MyList.Any(l => l.Id == Id) Application[Id.ToString()] = null; 
} 

Ich habe eine Möglichkeit gedacht, wie das Hinzufügen der Id, um seinen Wert wie:

for(int i=0;i<MyList.Count;i++) 
    Application[MyList[i].Id.ToString()] = MyList[i].Id.ToString() + "," + MyList[i].Value; 

Und dann:

for(int i=0;i<Application.Count;i++) 
{ 
    int Id = int.Parse(Application[i].Split(',')[0]); 
    if(!MyList.Any(l => l.Id == Id) Application[Id.ToString()] = null; 
} 

aber scheint nicht die richtige Weg, es zu tun. Ich denke, es muss einen Weg geben, den Schlüssel zu bekommen, richtig?

Antwort

2

können Sie die AllKeys Sammlung verwenden:

foreach (string key in Application.AllKeys) 
{ 
    int id; 
    if (Int32.TryParse(key, out id)) 
    { 
     if (!MyList.Any(l => l.Id == id)) 
     { 
      Application.Remove(key); 
     } 
    } 
} 
+1

Große Antwort. Danke vielmals. Warum habe ich nicht an AllKeys gedacht? es ist peinlich –