C # List Usage

Source: Internet
Author: User

problem. You are questions about the List collection in the. NET Framework, which are located in the System.Collections.Generic Nam Espace. You want to see examples of using List and also explore some of the many useful methods it provides, making it a ideal Ty PE 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 is dynamic arrays in the C # language.                  They can grow as needed when you add elements.                They is 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 can I create a new List of unspecified size, and add four prime numbers to it. Importantly, the angle brackets is part of the declaration type, not conditional operators that mean less or more than. They is treated differently in the language.

~ ~ ~ Program This 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 can I 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 can I loop through your List with for and foreach loops. This was a very common operation when using List. The syntax is the same as, which is a 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 a fast to access, Ifyou avoid the Count () extension method. Count is equal to Length on arrays. See the sections "clearing List" for a example on using the Count property.

4. Clearing list-setting to NULL

Here are the along with the " the", "the" and "the" Count property, the "to erase all" elements in your List. Before Clear is called, the This List has 3 elements; After Clear are 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-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 their values from it.

---program this 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's useful to use the List constructor code here to create a new listfrom Dictionary keys. This would give you a List of the Dictionary keys. The array element type must match the type of the List elements, or the compiler would refuse to compile your code.

6. Finding elements

Here we an example the how can test each element in your List for a certain value. This shows the Foreach loop, which tests to see if 3 are in the the List of prime numbers. Note that + Advanced List methods is 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 This uses foreach on List (C #) ~ ~ ~
Using system;using system.collections.generic;class program{    static void Main ()    {        //New list for example< C3/>list<int> primes = new list<int> (new int[] {2, 3, 5});        See if List contains 3        foreach (int number in primes)        {            if (number = = 3)//would match once            {                Conso Le. WriteLine ("Contains 3");}}}    

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

7. Using capacity

You can use the capacity property on List, or pass a integer into the constructor, to improve allocation perform ance when using List. The author ' s 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 had never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing if the list was at more than percent of capacity". [List (T). TrimExcess METHOD-MSDN]

8. Using BinarySearch

You can use the binary search algorithm in the 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 a example of these methods on this site. [C # List AddRange use-dotnetperls.com]

Using ForEach method

Sometimes want to write a regular foreach loop, which makes foreach useful. This accepts an Action, which is a void delegate method. Be very cautious if 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 would return true also. Else, it'll return false.

One. Using join-string List

Here we see how you can use string. Join on a List of strings. This was 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 are that no trailing comma are present on the resulting string, which would being 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 t o Join        list<string> cities = new list<string> ();        Cities. ADD ("New York");        Cities. ADD ("Mumbai");        Cities. ADD ("Berlin");        Cities. ADD ("Istanbul");        Join strings to one CSV line        string line = string. Join (",", cities. ToArray ());        Console.WriteLine (line);    }}

= = = Output of the program = = =
New York,mumbai,berlin,istanbul

Getting List from the Keys in Dictionary

Here we see how can I use the list constructor to get a list of keys in your Dictionary collection. This gives your simple-to-iterate over Dictionary keys, or store them elsewhere. The Keys instance property accessor in Dictionary returns an enumerable collection Ofkeys, which can is 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

Inserting elements

Here's how can I insert an element into the your List at any position. The string "Dalmation" is inserted to index 1, which makes it become the second element in the List. Note if you had 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 This 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.WR Iteline (dog);}}}    

~ ~ ~ Output of the program ~ ~ ~Spanieldalmationbeagle
removing elements

The removal methods on List is covered in depth and 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]

Sorting and reversing

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

Converting List to Array

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

Getting Range of elements

Here we see how can I get a range of elements in your List collection using the GetRangeinstance method. This was similar to the take and Skip methods from LINQ, but had different syntax.

---program this 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, Range)        {            Console.WriteLine (river);}}    }

---Outputof the program---Amazonyangtze
Testing Lists for Equality

Sometimes need to test the Lists for equality, even when their elements is unordered. Sorting both of them and then comparing, or by using a custom List equality method. This site contains an example of a method, a tests lists for equality on an unordered. [C # List Element equality-dotnetperls.com]

. Using List with structs

When using the 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 a advanced optimization. Note that in many cases using structs would actually decrease the performance when they is used as parameters in methods s Uch as those on the List type.

Using var keyword

Here's how can I use List collections with the var keyword. This can greatly shortenyour lines of code, which sometimes improves readability. The var keyword have no effect on performance and only readability for programmers.

~ ~ ~ Program This 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    }}

Summary.

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



The List class is a generic equivalent class of the ArrayList class, and in some cases it is more convenient than using arrays and ArrayList.

We assume that there is a set of data, where each data is a structure.

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

Note that a struct cannot assign a value to an instance field, that is, the public int Id = 1 is wrong.

Using System.Collections.Generic;

list<item> items = new list<item> ();

Add to
Item item1 = new Item ();
Item1. Id = 0;
Item1. DisplayText = "Mercury";
Items. ADD (ITEM1);

Add to
Item ITEM2 = new Item ();
Item2. Id = 1;
Item2. DisplayText = "Earth";
Items. ADD (ITEM2);

Modify
The structure is used here, so it cannot be used directly with items[1]. DisplayText = "Venus"; if Item is a class, it can be used directly. Why is it? Because structs are passed by value.
Item item = Items[1];
Item. DisplayText = "Venus";
ITEMS[1] = Item;

C # List Usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.