【问题标题】:First or Last element in a List<> in a foreach loopforeach 循环中 List<> 中的第一个或最后一个元素
【发布时间】:2014-04-17 04:30:32
【问题描述】:

我有一个List&lt;string&gt;,我想识别列表中的第一个或最后一个元素,以便识别与该项目相关的不同功能。

例如。

foreach (string s in List)
{
    if (List.CurrentItem == (List.Count - 1))
    {
        string newString += s;
    }
    else
    {
        newString += s + ", ";
    }
}

我将如何定义List.CurrentItem?在这种情况下,for 循环会更好吗?

【问题讨论】:

    标签: c# list foreach


    【解决方案1】:

    宁可利用String.Join

    连接指定数组的元素或数组的成员 集合,在每个元素之间使用指定的分隔符或 会员。

    这要简单得多。

    类似

            string s = string.Join(", ", new List<string>
            {
                "Foo",
                "Bar"
            });
    

    【讨论】:

      【解决方案2】:

      您可以使用基于 linq 的解决方案

      例子:

      var list = new List<String>();
      list.Add("A");
      list.Add("B");
      list.Add("C");
      
      String first = list.First();
      String last = list.Last();
      List<String> middle_elements = list.Skip(1).Take(list.Count - 2).ToList();
      

      【讨论】:

      • 如果你的列表只有 1 个元素会怎样?
      • 这是一个非常特殊的情况,使用上面的例子之前必须进行预检查!
      【解决方案3】:

      你可以像这样使用计数器

               int counter = 0 ;
               foreach (string s in List)
               {
                     if (counter == 0) // this is the first element
                      {
                        string newString += s;
                      }
                     else if(counter == List.Count() - 1) // last item
                      {
                      newString += s + ", ";
                      }else{
                       // in between
                     }
                      counter++;
             }
      

      【讨论】:

        【解决方案4】:

        试试这样的:

        string newString = "";
        
        foreach (string s in List)
        {
          if( newString != "" )
            newString += ", " + s;
          else
            newString += s;
        }
        

        【讨论】:

          猜你喜欢
          • 2016-02-22
          • 2015-04-18
          • 2018-11-03
          • 1970-01-01
          • 2014-05-22
          • 1970-01-01
          • 2019-10-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多