Posted By

sureshdasari on 10/15/18


Tagged

csharp programming collections technology tutlane


Versions (?)

List in C# with Examples


 / Published in: C#
 

URL: https://www.tutlane.com/tutorial/csharp/csharp-list

In c#, List is a generic type of collection so it will allow to store only strongly typed objects i.e. an elements of same data type and the size of list will vary dynamically based on our application requirements like adding or removing an elements from the list.

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5.  
  6. namespace Tutlane
  7.  
  8. {
  9.  
  10. class Program
  11.  
  12. {
  13.  
  14. static void Main(string[] args)
  15.  
  16. {
  17.  
  18. // Creating and initializing list
  19.  
  20. List<int> lst = new List<int>();
  21.  
  22. lst.Add(1);
  23.  
  24. lst.Add(8);
  25.  
  26. lst.Add(45);
  27.  
  28. List<string> lst2 = new List<string>();
  29.  
  30. lst2.Add("Hi");
  31.  
  32. lst2.Add("Welcome");
  33.  
  34. lst2.Add("to");
  35.  
  36. lst2.Add("Tutlane");
  37.  
  38. Console.WriteLine("List1 Elements Count: " + lst.Count);
  39.  
  40. Console.WriteLine("List1 Capacity: " + lst.Capacity);
  41.  
  42. Console.WriteLine("*********List1 Elements********");
  43.  
  44. // Accessing list elements
  45.  
  46. foreach (var item in lst)
  47.  
  48. {
  49.  
  50. Console.WriteLine(item);
  51.  
  52. }
  53.  
  54. Console.WriteLine("List2 Elements Count: " + lst2.Count);
  55.  
  56. Console.WriteLine("List2 Capacity: " + lst2.Capacity);
  57.  
  58. Console.WriteLine("*********List2 Elements********");
  59.  
  60. foreach (var item in lst2)
  61.  
  62. {
  63.  
  64. Console.WriteLine(item);
  65.  
  66. }
  67.  
  68. Console.ReadLine();
  69.  
  70. }
  71.  
  72. }
  73.  
  74. }

Report this snippet  

You need to login to post a comment.