【问题标题】:How to get the data from list without using iterator in c#如何在不使用C#中的迭代器的情况下从列表中获取数据
【发布时间】:2011-07-10 22:36:12
【问题描述】:

我有一个包含一组字符串的列表,我想根据索引获取列表中存在的数据,而不使用迭代器。有没有像 get() 或 getat() 这样的函数使用某种方法我们可以取吗?

【问题讨论】:

  • 提供更多细节,如 list 是 List 还是其他一些集合?

标签: c# .net list iterator containers


【解决方案1】:

myList[index] 是要走的路

List<string> myList = new List<string>();
myList.Add("string 1");
myList.Add("String 2");

Console.WriteLine(myList[0]); // string 1
Console.WriteLine(myList[1]); // String 2

【讨论】:

    【解决方案2】:
    List<string> myList = new List<string();
    //add some elements to the list
    //then get the third element
    string thirdElement = myList[2];
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      item = list[i];
      

      【讨论】:

        【解决方案4】:

        使用重载的索引运算符。

        List<String> list; // ... initialize, populate list
        String element = list[1]; // get the element at index 1
        

        【讨论】:

          【解决方案5】:

          如果您的集合实现IList&lt;T&gt;,只需使用索引器。否则,如果您的集合只允许只进访问(即只实现IEnumerable&lt;T&gt;),您可以使用ElementAt() 方法,但它仍然使用引擎盖下的迭代器。

          【讨论】:

            【解决方案6】:

            我不知道您到底在说什么类型的列表,但 .net 中的大多数集合都有 CopyTo 函数,您可以使用 [] 运算符访问单个项目。

            【讨论】:

              【解决方案7】:
              List<string> list = new List<string>();
              list.Add("lots of strings");
              
              //If you want to print all the strings you can do:
              foreach(string str in list)
                 Console.WriteLine(str);
              
              //If you want to modify each string in the list, make each lower case for example, 
              // you can do. this is working by using the index of the elements in the list:
              for(int i = 0; i < list.Count; i++)
                 list[i] = list[i].ToLower();
              

              【讨论】:

                【解决方案8】:

                如果您使用通用类型 List(或 IList 的其他实现),您可以使用索引运算符直接访问特定位置的项目:item = myList[3]

                如果您使用仅实现 IEnumerable 的类型,则应使用 ElementAt() 函数。

                您避免使用迭代器的原因是什么?

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-02-06
                  • 2017-07-15
                  • 1970-01-01
                  • 2021-09-17
                  • 2017-05-24
                  • 2021-05-04
                  • 1970-01-01
                  相关资源
                  最近更新 更多