写在粘贴复制前:英文的感觉也可以,也能看的懂,多看看英文资料没坏处的

Problem. You have questions about the List collection in the .NET Framework, which is located in the System.Collections.Generic namespace. You want to see examples of using List and also explore some of the many useful methods it provides, making it an ideal type for dynamically adding data. Solution. This document has lots oftips and resources on the List constructed type, with examples using the C# programming language.

--- Key points: ---                                           
Lists are dynamic arrays in the C# language.
They can grow as needed when you add elements.
They are called generic collections and constructed types.
You need to use < and > in the List declaration.

1. Adding values

Here we see how to declare a new List of int values and add integers to it. This example shows how you can create a new List of unspecified size, and add four prime numbers to it. Importantly, the angle brackets are part of the declaration type, not conditional operators that mean less or more than. They are treated differently in the language.

~~~ Program that adds elements to List (C#) ~~~
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(5);
list.Add(7);
}
}

Adding objects. The above example shows how you can add a primitive type such as integer to a List collection, but the List collection can receive reference types and object instances. There is more information on adding objects with the Add method on this site. [C# List Add Method- dotnetperls.com]

2. Loops

Here we see how you can loop through your List with for and foreach loops. This is a very common operation when using List. The syntax is the same as that for an array, except your use Count, not Length for the upper bound. You can also loop backwards through your List by reversing the for loop iteration variables. Start with list.Count - 1, and proceed decrementing to >= 0.

~~~ Program that loops through List (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(7);
foreach (int prime in list) // Loop through List with foreach
{
Console.WriteLine(prime);
}
for (int i = 0; i < list.Count; i++) // Loop through List with for
{
Console.WriteLine(list[i]);
}
}
}

~~~ Output of the program ~~~ (Repeated twice) 2 3 7

3. Counting elements

To get the number of elements in your List, access the Count property. This is fast to access, if you avoid the Count() extension method. Count is equal to Length on arrays. See the section "Clearing List" for an example on using the Count property.

4. Clearing List—setting to null

Here we see how to use the Clear method, along with the Count property, to erase all the elements in your List. Before Clear is called, this List has 3 elements; after Clear is called, it has 0 elements. Alternatively, you can assign the List to null instead of calling Clear, with similar performance. However, after assigning to null, you must call the constructor again.

=== Program that counts List (C#) ===
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<bool> list = new List<bool>();
list.Add(true);
list.Add(false);
list.Add(true);
Console.WriteLine(list.Count); // 3
list.Clear();
Console.WriteLine(list.Count); // 0
}
}

=== Output of the program === 3 0

5. Copying array to List

Here we see an easy way to create a new List with the elements in an array that already exists. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and fills its values from it.

--- Program that copies array to List (C#) ---
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr = new int[3]; // New array with 3 elements
arr[0] = 2;
arr[1] = 3;
arr[2] = 5;
List<int> list = new List<int>(arr); // Copy to List
Console.WriteLine(list.Count); // 3 elements in List
}
}

--- Output of the program --- Indicates number of elements. 3

Notes on the example. It is useful to use the List constructor code here to create a new List from Dictionary keys. This will give you a List of the Dictionary keys. The array element type must match the type of the List elements, or the compiler will refuse to compile your code.

6. Finding elements

Here we an example of how you can test each element in your List for a certain value. This shows the foreach loop, which tests to see if 3 is in the List of prime numbers. Note that more advanced List methods are available to find matches in the List, but they often aren't any better than this loop. They can sometimes result in shorter code. [C# List Find Methods for Searching List- dotnetperls.com]

~~~ Program that uses foreach on List (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// New list for example
List<int> primes = new List<int>(new int[] { 2, 3, 5 });
// See if List contains 3
foreach (int number in primes)
{
if (number == 3) // Will match once
{
Console.WriteLine("Contains 3");
}
}
}
}

~~~ Output of the program ~~~ Contains 3

7. Using capacity

You can use the Capacity property on List, or pass an integer into the constructor, to improve allocation performance when using List. The author's research shows that capacity can improve performance by nearly 2x for adding elements. Note however that this is not usually a performance bottleneck in programs that access data. [C# Capacity Property- dotnetperls.com]

TrimExcess method. There is the TrimExcess method on List as well, but its usage is very limited and I have never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing if the list is at more than 90 percent of capacity". [List(T).TrimExcess Method- MSDN]

8. Using BinarySearch

You can use the binary search algorithm on List with the instance BinarySearch method. Binary search uses guesses to find the correct element much faster than linear searching. It is often much slower than Dictionary. [C# BinarySearch List- dotnetperls.com]

9. Using AddRange and InsertRange

You can use AddRange and InsertRange to add or insert collections of elements into your existing List. This can make your code simpler. See an example of these methods on this site. [C# List AddRange Use- dotnetperls.com]

10. Using ForEach method

Sometimes you may not want to write a regular foreach loop, which makes ForEach useful. This accepts an Action, which is a void delegate method. Be very cautious when you use Predicates and Actions, because they can decrease the readability ofyour code.

Another useful method. There is a TrueForAll method that accepts a Predicate. If the Predicate returns true for each element in your List, the TrueForAll method will return true also. Else, it will return false.

11. Using Join—string List

Here we see how you can use string.Join on a List of strings. This is useful when you need to turn several strings into one comma-delimited string. It requires the ToArray instance method on List. The biggest advantage ofJoin here is that no trailing comma is present on the resulting string, which would be present in a loop where each string is appended.

=== Program that joins List (C#) ===
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// List of cities we need to join
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
// Join strings into one CSV line
string line = string.Join(",", cities.ToArray());
Console.WriteLine(line);
}
}

=== Output of the program === New York,Mumbai,Berlin,Istanbul

12. Getting List from Keys in Dictionary

Here we see how you can use the List constructor to get a List of keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys, or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection ofkeys, which can be passed to the List constructor as a parameter.

::: Program that converts Keys (C#) :::
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Populate example Dictionary
var dict = new Dictionary<int, bool>();
dict.Add(3, true);
dict.Add(5, false);
// Get a List of all the Keys
List<int> keys = new List<int>(dict.Keys);
foreach (int key in keys)
{
Console.WriteLine(key);
}
}
}

::: Output of the program ::: 3, 5

13. Inserting elements

Here we see how you can insert an element into your List at any position. The string "dalmation" is inserted into index 1, which makes it become the second element in the List. Note that if you have to Insert elements extensively, you should consider the Queue and LinkedList collections for better performance. Additionally, a Queue may provide clearer usage ofthe collection in your code.

~~~ Program that inserts into List (C#) ~~~
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> dogs = new List<string>(); // Example List
dogs.Add("spaniel"); // Contains: spaniel
dogs.Add("beagle"); // Contains: spaniel, beagle
dogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagle
foreach (string dog in dogs) // Display for verification
{
Console.WriteLine(dog);
}
}
}

~~~ Output of the program ~~~
spaniel
dalmation
beagle

14. Removing elements

The removal methods on List are covered in depth in another article on this site. It contains examples for Remove, RemoveAt, RemoveAll, and RemoveRange, along with the author's notes. [C# List Remove Methods- dotnetperls.com]

15. Sorting and reversing

You can use the powerful Sort and Reverse methods in your List collection. These allow you to order your List in ascending or descending order. Additionally, you can use Reverse even when your List is not presorted. There is more information on these topics, as well as sorting your List with LINQ on a property on this site. [C# Sort List Method, Sorting and Reversing Lists- dotnetperls.com]

16. Converting List to array

You can convert your List to an array of the same type using the instance method ToArray. There are examples of this conversion, and the opposite, on this site. [C# Convert List to Array- dotnetperls.com]

17. Getting range of elements

Here we see how you can get a range of elements in your List collection using the GetRange instance method. This is similar to the Take and Skip methods from LINQ, but has different syntax.

--- Program that gets ranges from List (C#) ---
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> rivers = new List<string>(new string[]
{
"nile",
"amazon", // River 2
"yangtze", // River 3
"mississippi",
"yellow"
});
// Get rivers 2 through 3
List<string> range = rivers.GetRange(1, 2);
foreach (string river in range)
{
Console.WriteLine(river);
}
}
}

--- Output of the program ---
amazon
yangtze

18. Testing Lists for equality

Sometimes you may need to test two Lists for equality, even when their elements are unordered. You can do this by sorting both of them and then comparing, or by using a custom List equality method. This site contains an example of a method that tests lists for equality in an unordered way. [C# List Element Equality- dotnetperls.com]

19. Using List with structs

When using List, you can improve performance and reduce memory usage with structs instead of classes. A List of structs is allocated in contiguous memory, unlike a List of classes. This is an advanced optimization. Note that in many cases using structs will actually decrease the performance when they are used as parameters in methods such as those on the List type.

20. Using var keyword

Here we see how you can use List collections with the var keyword. This can greatly shorten your lines of code, which sometimes improves readability. The var keyword has no effect on performance, only readability for programmers.

~~~ Program that uses var with List (C#) ~~~
using System.Collections.Generic;
class Program
{
static void Main()
{
var list1 = new List<int>(); // <- var keyword used
List<int> list2 = new List<int>(); // <- Is equivalent to
}
}
21. Summary

Here we saw lots of examples with the List constructed type. You will find that List is powerful and performs well. It provides flexible allocation and growth, making it much easier to use than arrays. In most programs that do not have memory or performance constraints and must add elements dynamically, the List constructed type in the C# programming language is ideal.

List 用法和实例(转载)的更多相关文章

  1. java中List的用法和实例详解

    java中List的用法和实例详解 List的用法List包括List接口以及List接口的所有实现类.因为List接口实现了Collection接口,所以List接口拥有Collection接口提供 ...

  2. nn.moduleList 和Sequential由来、用法和实例 —— 写网络模型

    对于cnn前馈神经网络如果前馈一次写一个forward函数会有些麻烦,在此就有两种简化方式,ModuleList和Sequential.其中Sequential是一个特殊的module,它包含几个子M ...

  3. Python验证码识别处理实例(转载)

    版权声明:本文为博主林炳文Evankaka原创文章,转载请注明出处http://blog.csdn.net/evankaka 一.准备工作与代码实例 1.PIL.pytesser.tesseract ...

  4. Java WebService 简单实例[转载]

    [注意,本文转载自  http://hyan.iteye.com/    ] 一.准备工作(以下为本实例使用工具) 1.MyEclipse10.7.1 2.JDK 1.6.0_22 二.创建服务端 1 ...

  5. linux shell 流程控制(条件if,循环【for,while】,选择【case】语句实例 --转载

    http://www.cnblogs.com/chengmo/archive/2010/10/14/1851434.html nux shell有一套自己的流程控制语句,其中包括条件语句(if),循环 ...

  6. vsftpd虚拟用户创建实例(转载)

    vsftpd虚拟用户创建实例 发布:theboy   来源:net     [大 中 小] vsftpd虚拟用户创建实例,有需要的朋友可以参考下.  vsftpd虚拟用户创建实例,有需要的朋友可以参考 ...

  7. Java元组Tuple使用实例--转载

    原文地址:http://50vip.com/35.html 一.为什么使用元组tuple? 元组和列表list一样,都可能用于数据存储,包含多个数据:但是和列表不同的是:列表只能存储相同的数据类型,而 ...

  8. Dubbo入门实例--转载

    原文地址:http://blog.csdn.net/ruishenh/article/details/23180707?utm_source=tuicool 1.   概述 Dubbo是一个分布式服务 ...

  9. 分享php中四种webservice实现的简单架构方法及实例[转载]

    [转载]http://www.itokit.com/2012/0417/73615.html 本人所了解的webservice有以下几种:PHP本身的SOAP,开源的NUSOAP,商业版的PHPRPC ...

随机推荐

  1. vb6保存项目到c盘的安装目录

    工程保存在安装目录("C:\Program Files (x86)\Microsoft Visual Studio\VB98\errhandler1.vbp")里. 文件管理器找不 ...

  2. Bad Request - Request Too Long

    Bad Request - Request Too Long HTTP Error 400. The size of the request headers is too long. 该错误原因导致 ...

  3. Servlet中的常用类以及常用方法

    A:ServletConfig:用于读取Servlet在web.xml中配置的一些信息. getServletName(); getInitParameter();只能是Servlet自身下的参数设置 ...

  4. 史上最全的java随机数生成算法分享(转)

    这篇文章主要介绍了史上最全的java随机数生成算法,我分享一个最全的随机数的生成算法,最代码的找回密码的随机数就是用的这个方法 String password = RandomUtil.generat ...

  5. 【php】命名空间 和 自动加载的关系

    目的 本文的目的主要是说明 命名空间的 use 关键词 和 new ClassName 这两个步骤,哪个步骤才会执行自动加载,这是逻辑有点混乱的表现,这种想法也是很正常的,让我们来解密吧 命名空间(n ...

  6. selenium RC+JAVA 运行所遇到的问题

    1.报错一 Failed to start new browser session: java.lang.RuntimeException: Firefox 3 could not be found ...

  7. ios10 safari 的坑!

    | 导语 ios10 的safari,又给前端开发者挖坑了..测试验证此问题只出现在ios10 safari中.想早点知道结论的,可以直接看最后一个结论~因为,解决过程不重要! 个人原创,未经允许,禁 ...

  8. gvim初学命令记录

    一.vim进入和退出(在正常模式下进行)若不能保证是否处于正常模式,先按下ESC键不保存退出 :q!(冒号也是键的)保存退出 :wq二.移动 k(上)h(左) l(右) j(下)三.删除(可类似于剪切 ...

  9. gulp任务

    项目使用的gulp自动化任务 //定义输出文件夹名称 var distFolderH5 = "distH5"; var distFolderMofang = "distM ...

  10. Cen0S下挂载设备

    在CentOS中,如果我们要查看光驱,U盘或者要把安装包挂载到某个文件夹,我写下我的一些理解. 所谓的挂载,就是把物理设备或者文件(包含安装文件,压缩包等等),与系统中的某个目录建立一个快捷方式,然后 ...