C# List 用法与示例

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 类是 ArrayList 类的泛型等效类,某些情况下,用它比用数组和 ArrayList 都方便。

我们假设有一组数据,其中每一项数据都是一个结构。

public struct Item
{
    public int Id;
    public string DisplayText;
}

注意结构是不能给实例字段赋值的,即 public int Id = 1 是错误的。

using System.Collections.Generic;

List<Item> items = new List<Item>();

//添加
Item item1 = new Item();
item1.Id = 0;
item1.DisplayText = "水星";
items.Add(item1);

//添加
Item item2 = new Item();
item2.Id = 1;
item2.DisplayText = "地球";
items.Add(item2);

//修改
//这里使用的是结构,故不能直接用 items[1].DisplayText = "金星";,如果 Item 是类,则可以直接用。为什么呢?因为结构是按值传递的。
Item item = items[1];
item.DisplayText = "金星";
items[1] = item;

时间: 2024-10-16 19:48:59

C# List 用法与示例的相关文章

Web前端设计:Html强制不换行&lt;nobr&gt;标签用法代码示例

在网页排版布局中比如文章列表标题排版,无论多少文字均不希望换行显示,需要强制在一行显示完内容.这就可以nobr标签来实现.它起到的作用与word-break:keep-all 是一样的.nobr 是 No Break 的缩写,意思是禁止换行.通常在浏览器上显示的文档会在到达浏览器的横幅底端时自动换行,但是如果文字被包含在<nobr>-</nobr>标签里的话,则不会换行.由www.169it.com搜集整理 一.nobr语法 1 <nobr>内容</nobr>

(转)轻松掌握shell编程中数组的常见用法及示例

缘起:在老男孩进行linux培训shell编程教学中,发现不少水平不错的网友及同学对数组仍然很迷糊,下面就给大家分享下数组的用法小例子,希望能给大家一点帮助.其实SHELL的数组很简单,好用.我们学习都应该遵循简单.易用的原则. shell编程中数组的简单用法及示例 新版本的Bash支持一维数组. 数组元素可以使用符号variable[xx]等方式来初始化. 另外, 脚本可以使用declare -a variable语句来指定一个数组等.要引用一个数组元素(也就是取值), 可以使用大括号, 访问

SerialPort类的用法与示例

转:https://www.cnblogs.com/hwBeta/p/6926363.html Microsoft .Net框架SerialPort类的用法与示例 从Microsoft .Net 2.0版本以后,就默认提供了System.IO.Ports.SerialPort类,用户可以非常简单地编写少量代码就完成串口的信息收发程序.本文将介绍如何在PC端用C# .Net 来开发串口应用程序. 1. 串口硬件信号定义 DB9 Connector 信号定义 针脚 信号 定义 作用 1 DCD 载波

expect基础用法及示例

以下是一个可以使用的脚本 .在这种交互式的应用中,经常需要用到休眠函数,这样可以对输出的界面显示更加友好,而且也可能尽量多的减少 错误的出现 关于转义字符,网上存在一部分,本例中用到来-号需要转义,转义是用两个\来转义. \ 需转义为 \\\ } 需转义为 \} [ 需转义为 \[ $ 需转义为 \\\$ ` 需转义为 \` " 需转义为 \\\" 可以用log_user 0或1实现输出屏蔽和显示 log_file test.log   #记录log.追加 expect遵循的是tcl语

[Java] ThreadPool用法与示例

1.ThreadPool的优点 在java.util.concurrent包下,提供了一系列与线程池相关的类.合理的使用线程池,可以带来多个好处: (1)降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗: (2)提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行: (3)提高线程的可管理性.线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控. 线程池可以应对突然大爆发量的访问,通过有限个固定线程为

linux bash shell中for的用法and示例

关于linux bash shell中的for语句 在linux中shell是必不可少的一部分,但是在bash shell中有while,for,until等循环命令,今天就介绍一下关于for的一些用法.文中任何错误希望大佬们一一指出,不胜感激. bash shell中提供了for命令,用于创建通过一系列值重复的循环,每次重复使用系列中的一个值执行一个定义的命令集. for语句的基本格式如下: for---in list do commands done 在参数list中提供一系列用于迭代(上一

Handler, AsyncTask用法简单示例

package com.jim.testapp; import android.app.Activity; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import androi

IIS7.5 APPCMD 简单用法及示例

1 添加应用程序进城池 appcmd.exe add apppool  /name:test.com  /managedRuntimeVersion:"v4.0" /managedPipelineMode:"Integrated" 2 添加站点,指定站点名,绑定,物理路径 appcmd.exe add site /name:"test.com"  /id:1 /bindings:http/*:81:  /physicalpath:"E:

jquery.autocomplete.js用法及示例,小白进

8 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <html xmlns="http://www.w3

【Linux】Linux系统下find指令详细用法与示例

Linux中的Find指令是Linux系统中很重要也是很棒的指令之一,功能非常得强大.下面我根据实例代码向大家分享find指令.由于博客上无法贴出Linux代码,我就在截图中体现出代码,以及效果. 我先自己创建了文件名的test.c的普通文件,我们用指令mkdir,以及ls查看已经创建了test.c. 现在我们查找它. 根据文件名或者正则表达式查找:-name   通过文件名字查找 文件名: 1)find ./ -name test.c   查找文件名为test.c的文件 2)find ./ -