我有一个 Dictionary<int, DataRow>使用 ElementAt() 方法。它在 .NET 3.5 及更高版本中运行良好。但是,我的 ISP 似乎正在运行一些不理解该方法的 .NET 3.5 之前的版本,呈现以下错误:
Compiler Error Message: CS0117: 'System.Collections.Generic.Dictionary< int,System.Data.DataRow >' does not contain a definition for 'ElementAt'
我需要使用 ElementAt 的原因是因为我想随机选择字典元素,然后删除该元素,直到所有元素都随机显示
int key = testimonialDictionary.ElementAt(rnd).Key;
... do something with the Value / DataRow
testimonialDictionary.Remove(key);
我的问题是,人们在 ElementAt() 之前使用了什么?我该如何实现?
请您参考如下方法:
我相信这是实现它的简单方法
string ElementAt(Dictionary<string,string> dict, uint index)
{
if(dict.Count > index)
{
uint iCnt =0;
foreach(KeyValuePair<string,string> val in dict)
{
if(index == iCnt)
return val.Key;
iCnt++;
if(index < iCnt)
return null;
}
}
return null;
}
测试一下
Dictionary<string,string> dict = new Dictionary<string,string>{{"A","1"},{"B","2"},{"C","3"},{"D","4"},{"E","5"}};
for(uint i=0;i<5;i++)
Console.WriteLine(ElementAt(dict,i));
