Collection classes are specialized classes for data storage and retrieval.
These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.
Create and manage group of related object , Then there are two way to handle this first is array and second one is collection array are most useful for fixed and strongly type object.
Collection provide more flexible to work with group of object, group of object can shrink and grow dynamically.
for some collection when we need to assign a key to object then put into collection and retrive data using key.
A collection is a class, so you must declare a new collection before you can add elements to that
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Collection
- {
- class Program
- {
-
-
-
-
-
-
-
-
-
-
- static void Main(string[] args)
- {
- var sal = new List<string> { "I", "M", "collection" };
- sal.Add("Manu");
- sal.Add("Gupta");
- foreach (var a in sal)
- {
-
- Console.WriteLine("Data is " + a);
- }
- Cat cat = new Cat { Age = 10, Name = "Fluffy" }; { }
- List<Cat> cats = new List<Cat>
- {
- new Cat(){ Name = "US", Age=8 },
- new Cat(){ Name = "Delhi", Age=2 },
- new Cat(){ Name = "London", Age=14 }
- };
- Console.WriteLine("Generic is ...........");
- foreach (Cat c in cats)
- {
- Console.WriteLine("Generic is " + c);
- }
- var salint = new List<int>();
- salint.Add(1);
- salint.Add(2);
- foreach (var b in salint)
- {
- Console.WriteLine("Data is " + b);
- }
- salint.Remove(0);
- var obj = new List<string> { "Faizabad", "Patna", "Varanasi" };
- for (var index = 0; index < obj.Count;index++ )
- {
- Console.WriteLine("In for loop " +obj[index] );
- }
- var theGalaxies = new List<Galaxy>
- {
- new Galaxy { Name="Tadpole", MegaLightYears=400},
- new Galaxy { Name="Pinwheel", MegaLightYears=25},
- new Galaxy { Name="Milky Way", MegaLightYears=0},
- new Galaxy { Name="Andromeda", MegaLightYears=3}
- };
- foreach (Galaxy theGalaxy in theGalaxies)
- {
- Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears);
- }
- Console.ReadKey(true);
- }
- class Cat
- {
- public int Age { get; set; }
- public string Name { get; set; }
- }
- public class Galaxy
- {
- public string Name { get; set; }
- public int MegaLightYears { get; set; }
- }