【问题标题】:See if Dictionary Item is the last one in the dictionary查看 Dictionary Item 是否是字典中的最后一个
【发布时间】:2011-09-07 03:38:42
【问题描述】:

给定代码..

var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ? 

  // do something if this is the last item
});

我基本上想看看我在 ForEach 迭代中使用的项目是否是字典中的最后一个项目。我试过了

bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;

但这没有用......

【问题讨论】:

  • 您是否尝试过使用计数器并将通过 foreach 的迭代与字典的大小进行比较?字典理论上是无序的,所以我不相信任何与字典的 Last 值的比较。
  • 字典中的“最后”到底是什么?
  • 这个问题没有多大意义,因为Dictionary 集合没有排序。看看这个:Why is a Dictionary “not ordered”?

标签: c# linq dictionary


【解决方案1】:

使用System.Linq命名空间,我们可以做到 MyDictionary[item.Key].Equals( MyDictionary.Last().Key ); Last() 方法应该向我们展示每个数组、字典、列表、堆栈、队列中的最后一个元素。

【讨论】:

    【解决方案2】:

    有人提到将迭代中当前项的与上一项的值进行比较,例如:

        dictionary[item.Key].Equals(dictionary.Last().Value) 
    

    警告:如果字典中的任何项的值等于字典中最后一项的值,这可能导致字典中的任何项为真。这并不表示该项目是字典中的最后一个项目。


    相反,如果您真的想查找迭代中的当前项是否是最后一项,我建议您比较密钥,因为您知道它是唯一的,所以它可能看起来像:

        item.Key.Equals(dictionary.Last().Key)
    

    【讨论】:

      【解决方案3】:

      您始终可以使用计数器来执行此操作。

      int itemsCount = yourDictionary.Count;
      bool isLast = false;
      
      foreach(var item in yourDictionary)
      {
         itemsCount--;       
         isLast = itemsCount == 0; 
      
         if(isLast)
         {
           // this is the last item no matter the order of the dictionary        
         }
         else
        {
          //not the last item
        }
      
      }
      

      【讨论】:

        【解决方案4】:

        只对循环外的最后一项执行操作不是更简单吗?

        string requiredForSomething = dictionary.Last().Value;
        

        【讨论】:

          【解决方案5】:

          首先,Dictionary 甚至 IEnumerable 没有 ForEach 扩展方法。所以你必须先解决这个问题。

          其次,Last 扩展方法将非常缓慢,因为它必须枚举整个集合。

          第三,我不确定对具有不可预测顺序的集合中的最后一项进行特殊处理是否有意义,但这主要与您的具体问题无关。

          这是我解决问题的方法。创建两个在 IEnumerable&lt;T&gt; 实例上运行的新扩展方法。 ForEach 将等效于 List&lt;T&gt;.ForEach 方法,WithIndex 将返回另一个包含顺序索引和 IsLast 标志的枚举数。这是another one of my answers 对类似问题的变体。

          dictionary.WithIndex().ForEach(
            (item) =>
            {
              var kvp = item.Value; // This extracts the KeyValuePair
              if (item.IsLast)
              {
                Console.WriteLine("Key=" + kvp.Key.ToString() + "; Value=" + kvp.Value.ToString());
              }
            });
          

          这是新的扩展方法。

          public static class ForEachHelperExtensions
          {
              public sealed class Item<T>
              {
                  public int Index { get; set; }
                  public T Value { get; set; }
                  public bool IsLast { get; set; }
              }
          
              public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
              {
                  foreach (T item in enumerable)
                  {
                      action(item);
                  }
              }
          
              public static IEnumerable<Item<T>> WithIndex<T>(this IEnumerable<T> enumerable)
              {
                  Item<T> item = null;
                  foreach (T value in enumerable)
                  {
                      Item<T> next = new Item<T>();
                      next.Index = 0;
                      next.Value = value;
                      next.IsLast = false;
                      if (item != null)
                      {
                          next.Index = item.Index + 1;
                          yield return item;
                      }
                      item = next;
                  }
                  if (item != null)
                  {
                      item.IsLast = true;
                      yield return item;
                  }
              }
          }
          

          【讨论】:

            【解决方案6】:

            Dictionary.Last 返回一个KeyValuePair,您将其与键的值进行比较。你需要检查:

            dictionary[item.Key].Equals( dictionary.Last().Value )

            IAbstract 也是正确的,您可能需要使用 OrderedDictionary。

            【讨论】:

            • 谢谢,我没想到。
            【解决方案7】:

            你可以测试 value == dictionary.Values.Last();

            【讨论】:

              【解决方案8】:

              您将需要使用OrderedDictionary&lt;TKey, TValue&gt;。检查MSDN ref.

              使用标准字典,不保证项目以任何特定顺序持久化。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2013-01-06
                • 1970-01-01
                • 1970-01-01
                • 2020-01-27
                • 1970-01-01
                • 2012-03-08
                • 1970-01-01
                相关资源
                最近更新 更多