【问题标题】:I need the Index of the last item in a List, how?我需要列表中最后一项的索引,如何?
【发布时间】:2020-02-12 11:26:15
【问题描述】:

所以,我已经搜索了一段时间,但没有真正找到任何结果。 例如我有这个列表: List<int> intList = new List<int>{1, 2, 3, 4, 1} 我想在我的控制台中输出“数字:1、2、3、4 和 1”,这并不难。但我希望能够使用用户输入的数字,并且对于最后一个数字,它必须在数字之前有“和”而不是逗号。到目前为止我尝试过的事情导致了任何具有相同值的项目也有“和”而不是逗号的问题。

我在 for 循环中的 if 语句中使用的示例导致任何与最后一个相同的值也具有“and”: if (intList[i] == intList.Last()) if(intList[i] == intList[intList.Count - 1])

在我看来,为什么这些不起作用是合乎逻辑的,但理解问题并解决它仍然是两件不同的事情。

【问题讨论】:

    标签: c#


    【解决方案1】:

    .Last() 之前加入所有内容,然后与" and " + Last() 连接,例如:

     string result = intList.Count <= 1 ?
           string.Join(", ", intList) :
           string.Join(", ", intList.Take(intList.Count - 1)) + " and " + intList.Last(); 
    

    【讨论】:

      【解决方案2】:

      有时蛮力是要走的路。考虑这样的事情:

      private string ConcatInts()
      {
          List<int> intList = new List<int> {1, 2, 3, 4, 1};
          var buffer = new StringBuilder();
          var len = intList.Count;
          for (var i = 0; i < len; ++i)
          {
              if (i > 0 && i < len - 1)
              {
                  buffer.Append(", ");
              }
              else if (i == len - 1)
              {
                  buffer.Append(", and ");
              }
              buffer.Append(intList[i].ToString());
          }
      
          return buffer.ToString();
      }
      

      我通常不喜欢对 List 进行索引(我喜欢将它们视为列表),但它们确实很好地支持索引。

      【讨论】:

      • “我喜欢将它们视为列表”是什么意思?你的意思是列表列表吗?在列表中建立索引是否有任何“坏”的东西?我想知道。
      • @LouisGo:列表的典型访问模式是枚举它,从头到尾(对于单链表)或者可能在任一方向(对于双链表)。即使实现不是基于链表,一个列表的总是有效访问模式是迭代。就像数组的一个始终有效访问模式是索引。一些列表实现在通过索引访问时性能很差。然而,.NET List&lt;T&gt; 背后有一个数组支持,因此索引工作得很好。不过,在我看来,我远离索引列表
      • 我明白你的意思。感谢您的解释。只考虑.Net List&lt;T&gt;
      【解决方案3】:

      也许这段代码可以帮助你

      using System;
      using System.Collections.Generic;
      
      public class Program
      {
          public static void Main()
          {
              List<int> intList = new List<int>{1,2,3,4,1};
              System.Console.WriteLine("Elements: \r\n");
              for(int index =0; index < intList.Count-1; index++)
              {
                  System.Console.Write(intList[index].ToString());
                  System.Console.Write(", ");
              }
              if(intList.Count > 1)
                  System.Console.Write("and ");
              if(intList.Count > 0)
                  System.Console.Write(intList[intList.Count-1]);     
              else
                  System.Console.Write("<<Empty List>>");
          }
      }
      

      【讨论】:

        【解决方案4】:

        您还可以使用 GetRange 创建原始列表的浅表副本并排除最后一个元素。

            static void Main(string[] args)
            {
                List<int> intList = new List<int> {1, 2, 3, 4, 1};
                List<int> allButLast = intList.GetRange(0, intList.Count - 1);
                string last = intList.Last().ToString();
                string allButLastString = string.Join(',', allButLast);
                Console.WriteLine($"{allButLastString} and {last}");
            }
        

        【讨论】:

          【解决方案5】:

          如果不需要太高效,可以这样作弊:

           var result = string.Join(", ", intList);
           var lastCommaIndex = result.LastIndexOf(',');
           if (lastCommaIndex > 0)
           {
               result = result.Substring(0, lastCommaIndex) + " and" + result.Substring(lastCommaIndex + 1);
           }
          

          否则,@Alexei Levenkov 的回答大致就是我会做的。 :)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-12-14
            • 1970-01-01
            • 2019-05-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多