Net-informations.com
SiteMap  | About    

How to use C# List Class

List < T > Class

c# list example

The Collection classes are a group of classes designed specifically for grouping together objects and performing tasks on them. List class is a collection and defined in the System.Collections.Generic namespace and it provides the methods and properties like other Collection classes such as add, insert, remove, search etc. It's the replacement for arrays, linked lists, queues, and most other one-dimensional data structures. This is because it has all kinds of extra functionality, including the ability to grow in size on-demand.

The C# List < T > class represents a strongly typed list of objects that can be accessed by index and it supports storing values of a specific type without casting to or from object.

List < T >

The parameter T is the type of elements in the list.

c# add items in a list	 sample



Add Integer values in the List collection

List<int> iList = new List<int>(); iList.Add(2); iList.Add(3); iList.Add(5); iList.Add(7);

Add String values in the List

List<string> colors = new List<string>(); colors.Add("Red"); colors.Add("Blue"); colors.Add("Green");
c# count items in a list



How to find the size of a list?

You can use count property to know the number of items in the List collection or the length of a C# List

colors.Count
c# for each loop in a list

You can retrieve items from List collection by using for loops.

foreach loop

foreach (string color in colors) { MessageBox.Show(color); }

for loop

for (int i = 0; i < colors.Count; i++) { MessageBox.Show(colors[i]); }
c# insert items in a list

You can use insert(index,item) method to insert an in the specified index.

colors.Insert(1, "violet");

In the above code the color "violet" inserted in the index position 1.

How to sort a C# List

You can use the sort() method of C# List for ordering items in the List.

colors.Sort();

How to remove an item from List collection ?

Remove() can use to remove item from List collection.

colors.Remove("violet");

How to check if an item exist in the List collection ?

You can use List.Contains() methods to check an item exists in the List

if (colors.Contains("Blue")) { MessageBox.Show("Blue color exist in the list"); }

How to copy an Array to a List collection ?

string[] strArr = new string[3]; strArr[0] = "Red"; strArr[1] = "Blue"; strArr[2] = "Green"; //here to copy array to List List<string> arrlist = new List<string>(strArr);

How to Convert List to String in C#

You can convert a C# List to a string use the following method.

string combindedString = string.Join(",", colors);

The output look like "Red,Blue,Green"

You can replace the seperator to any character instead of ","

Convert List to Array in C#

You can convert a C# List to an Array using toArray() method.

string[] arr = colors.ToArray();

How to empty a list in C#?

Finally clear method remove all the items from List collection.

arrlist.Clear ();
c# List Vs Arraylist

In C# List is depend by array so the theoretical limit of size would be the limit of the array's capacity. Appending elements is efficient because we are using the free slots at the end, but inserting elements can be slow because all elements in the List after the insertion point have to be shifted to make a free slot. In case of searching, it is is efficient if the BinarySearch method is used on a list that has been sorted, if you use any other search algoritham is inefficient because each item must be individually checked.

List Vs Array

Arrays are memory-efficient. Lists are built on top of arrays. Because of this, Lists use more memory to store the same data. Array is useful when you know the data is fixed length, or unlikely to grow much. It is better when you will be doing lots of indexing into it, i.e. you know you will often want the third element, or the fifth, or whatever. On the other hand, if you don't know how many elements you'll have, use List. Also, definitely use a List any time you want to add/remove data, since resizing arrays is expensive.

How to get duplicate items from a list using LINQ

List<String> duplicates = lst.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList();

The GroupBy keyword groups the elements that are the same together, and the Where keyword filters out those that only appear once, leaving you with only the duplicates.

Difference between list and dictionary in C#

Both lists and dictionaries are used to store collections of data. List (ICollection ) is simply a set of items and Dictionary(IDictionary) is a set of key-value pairs. The essential difference therefore is in how the containers are indexed. If you want to know more details..... what is the difference between list and dictionary ?

The following C# program shows the implementation of the above functionalities in List collection.




using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List < string > colors = new List < string > ();

            //add items in a List collection
            colors.Add("Red");
            colors.Add("Blue");
            colors.Add("Green");

            //insert an item in the list
            colors.Insert(1, "violet");

            //retrieve items using foreach loop
            foreach (string color in colors)
            {
                MessageBox.Show(color);
            }

            //remove an item from list
            colors.Remove("violet");

            //retrieve items using for loop
            for (int i = 0; i < colors.Count; i++)
            {
                MessageBox.Show(colors[i]);
            }

            if (colors.Contains("Blue"))
            {
                MessageBox.Show("Blue color exist in the list");
            }
            else
            {
                MessageBox.Show("Not exist");
            }

            //copy array to list
            string[] strArr = new string[3];
            strArr[0] = "Red";
            strArr[1] = "Blue";
            strArr[2] = "Green";
            List < string > arrlist = new List < string > (strArr);

            foreach (string str in strArr)
            {
                MessageBox.Show(str);
            }

            //call clear method
            arrlist.Clear ();

            MessageBox.Show(arrlist.Count.ToString ());
        }
    }
}






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.