通过索引
问题描述:
获取应用国家重点名字我添加几个值到应用程序的状态,如:通过索引
for(int i=0;i<MyList.Count;i++)
Application[MyList[i].Id.ToString()] = MyList[i].Value;
然后我想删除值已到期(不在当前我的列表)的ID。所以我想遍历所有的应用程序状态值,并删除它们如果Id已过期。是这样的:
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;
}
我已经想到了一个办法像加了标识,以它的价值,如:
for(int i=0;i<MyList.Count;i++)
Application[MyList[i].Id.ToString()] = MyList[i].Id.ToString() + "," + MyList[i].Value;
然后:
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;
}
但似乎并不正确方法来做到这一点。我认为必须有一种方法来获得钥匙,对吧?
答
可以使用AllKeys
集合:
foreach (string key in Application.AllKeys)
{
int id;
if (Int32.TryParse(key, out id))
{
if (!MyList.Any(l => l.Id == id))
{
Application.Remove(key);
}
}
}
伟大的答案。非常感谢。为什么我没有想到AllKeys。它的尴尬 –