【问题标题】:how to find Next key using foreach in SortedDictionary in C#如何在 C# 的 SortedDictionary 中使用 foreach 查找 Next 键
【发布时间】:2013-06-14 10:03:53
【问题描述】:

我有一个已排序的字典,其中存储了字符串作为键和值。 并且我在某些条件下检查每个键的值。

void sample()
{
  SortedDictionary<string, string>.KeyCollection keyColl = clrDatesSelectedSortedDict.Keys;
  foreach (string key in keyColl)
   {
     if(chckstring = key)
      value = clrDatesSelectedSortedDict[key];
   }
 }

实际上,如果条件我也想知道下一个键。如何获取下一个键值?

还有一个问题,C# 中的 sortedDictionary 是否可以使用 for 循环而不是 foreach?

请帮助我上述任何一项。 提前致谢。

【问题讨论】:

    标签: c# foreach sorteddictionary


    【解决方案1】:

    怎么样

    Public Sub TestLoopForeachKey()
        Dim sd As New SortedDictionary(Of String, String)
        For i = 0 To sd.Count
            Dim nextIndex As Integer = i + 1
            If nextIndex < sd.Count Then
                ' Exists another posterior key
                Dim currentKey As String = sd(i)
                Dim nextKey As String = sd(nextIndex)
            End If
        Next
    End Sub
    

    【讨论】:

    • 您尝试使用sd(i) 进行索引将不起作用,因为键是String,而不是Integer
    • 是的,看起来我在单元测试中没有严格的选项,只是想展示一种方法;P
    【解决方案2】:

    当然,使用 Ling 扩展 ElementAt():

    void sample()
    {
        SortedDictionary<String, String>.KeyCollection keyColl = clrDatesSelectedSortedDict.Keys;
        for (Int32 i = 0; i < keyColl.Count; i++)
        {
            if (chckstring == keyColl.ElementAt(i).Key)
            {
                value = clrDatesSelectedSortedDict[keyColl.ElementAt(i).Key];
                if ((i + 1) < keyColl.Count)
                    nextValue = clrDatesSelectedSortedDict[keyColl.ElementAt(i + 1).key];
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-19
      • 2013-04-10
      • 1970-01-01
      • 2013-12-26
      • 2017-01-26
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多