Professional Documents
Culture Documents
n be accessed by index. This class provides methods to loop, filter, sort and manipulate collections. The non-generic version of this class is the ArrayList class.
This article focuses on some common operations of Generics List(T) class, First of all create a console application , open Visual Studio 2008 /2010 File > New Project >Console Application
Here I am using collection of Product class. So first of all we will create Product class . Add a Product class to application, right click on project >Add > Class and rename it Product.cs using using using using System; System.Collections.Generic; System.Linq; System.Text;
namespace GenericCollectionsOperation { public class Product { private int productID; private string name; private string categoryName; private int price; #region Properties Region public int ProductID { get; set; } public string Name { get; set; } public string CategoryName { get; set; } public int Price { get; set; } #endregion } }
Now go to Program.cs create Generic List Object [List(T)] and add Product objects to the List(T).
namespace GenericCollectionsOperation { class Program { static void Main(string[] args) { List<Product> products = new List<Product>() { new Product(){ProductID=1, =1,Name="Colgate", CategoryName="General" ,Price= 27}, new Product(){ProductID= 2 ,Name="Hair Oil",CategoryName="General" ,Price= 67}, new Product(){ProductID= 3 ,Name="Bottle",CategoryName="Crockery" ,Price=24}, new Product(){ProductID= 4 ,Name="Plate",CategoryName="Crockery" ,Price= 8}, new Product(){ProductID= 5 ,Name="Radio",CategoryName="Electronics" ,Price= 700}, new Product(){ProductID= 6 ,Name="BlueTooth",CategoryName="Electronics" ,Price= 1099} }; } } } Here We will Create a common Method to Print named PrintConsole .By Using this we can print List of Product items.
static void PrintOnConsole(List<Product> pList, string info) { Console.WriteLine(info); Console.WriteLine("\n{0,5} {1,7} {2,10} {3,14} ", "ProductID", "Name", "Category", "Price"); pList.ForEach(delegate(Product product) { Console.WriteLine("{0,5} {1,9} {2,13} {3,14}", product.ProductID, product.Name, product.CategoryName, product.Price); });
Now we Focuses on List(T) operation s 1-Looping through all items of List of objects of Products.
Here we can call this common method for looping the items of List(Product) PrintOnConsole(productList, "Looping Through All Products in List"); Console.Read();
Here is Output :
Here is Output:-
Here is output:_
Here is Output:_