通过SortedList进行迭代
本文关键字:迭代 SortedList 通过 | 更新日期: 2023-09-27 17:49:13
SortedList<string, systemuser> Users = new SortedList<string, systemuser>();
Users.Add("username1",customobject);
Users.Add("username2",customobject);
Users.Add("username3",customobject);
我要做的是搜索列表中的特定键(即用户名),并返回列表中的下一个项目。如果我在列表的末尾,那么我需要返回第一个位置的项。
不知道该怎么做,因为SortedList似乎没有暴露索引属性。
我:
foreach (KeyValuePair<string, systemuser> pair in Users)
{
if (pair.Key == lastAllocation)
{
// RETURN THE ITEM IMMEDIATELY AFTER THIS ONE
}
}
感谢任何建议!
首先获取查找元素的索引。然后获取所需的密钥(不要忘记模块%
)。终于能见到心爱的人了:))
SortedList<string, systemuser> Users = new SortedList<string, systemuser>();
Users.Add("username1",customobject);
Users.Add("username2",customobject);
Users.Add("username3",customobject);
var index = Users.IndexOfKey("username1"); // check not found if necessary
var nextItemKey = s.Keys[(index + 1) % Users.Count()];
var nextItemValue = Users.IndexOfKey(nextItemKey);
您是否正在寻找下一个项目(KeyValuePair),值或索引?
bool returnNextItem = false;
foreach (KeyValuePair<string, systemuser> pair in Users)
{
if (returnNextItem)
return pair.Value;
if (pair.Key == lastAllocation)
returnNextItem = true;
}
SortedList包含完成此操作所需的方法。看看IndexOfKey
和GetByIndex
。
当你调用foreach
时,你实际上是在调用Users.GetEnumerator();
。
是以下语句的语法糖:
KeyValuePair<String, Systemuser> pair;
IEnumerator<KeyValuePair<String, Systemuser>> enumerator = Users.GetEnumerator();
while (enumerator.MoveNext())
{
pair = enumerator.Current;
// your code in the foreach loop here
}
简单的解决方案是手动使用枚举器来执行您想要的操作。
KeyValuePair<String, Systemuser> getSomething(String lastAllocation)
{
IEnumerator<KeyValuePair<String, Systemuser>> enumerator = Users.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current.Key == lastAllocation)
{
enumerator.MoveNext();
return enumerator.Current; // null if not another
}
}
return null;
}
您可以使用IndexOfKey
查找给定用户名列表中的位置。
使用返回的索引,可以返回下一项,也可以返回列表中的第一项。
var idx = Users.IndexOfKey("username2");
if (idx == (Users.Count - 1)){
return Users.First().Key;
}
else{
return Users.Keys[idx + 1];
//.net 4.5+ can Users.GetByIndex()
}
你可以试试这个。不确定你想要什么,如果没有匹配,所以我们只是返回一个新的KeyValuePair;还要确保你有一个using System.Linq;因此您可以访问ElementAt扩展方法。
public static KeyValuePair<string, string> GetUserInfo(string username, SortedList<string, string> list)
{
int index = list.IndexOfKey(username);
if(index == -1)
{
return new KeyValuePair<string, string>();
}
index = index == (list.Count - 1) ? 0 : index + 1;
return list.ElementAt(index);
}
作为参考,SortedList有2个核心引用,一个在System中。Collections(旧的)和System.Collections.Generic。在处理System.Collections时。SortedList,我只能使用Microsoft文章(https://msdn.microsoft.com/en-us/library/system.collections.sortedlist(v=vs.110).aspx)中引用的迭代方法
下面是myList是SortedList集合的循环。
for ( int i = 0; i < myList.Count; i++ ) {
Console.WriteLine( "'t{0}:'t{1}", myList.GetKey(i), myList.GetByIndex(i) );
}
戴夫