Collections - List class - dotnet and db

Follow us on Facebook

SQL Server Mountain View Mountain View Mountain View

Saturday, July 21, 2018

Collections - List class




List can be used to create a list of elements of a specific datatype.

A list  which contains integer type as below
List<int> lEmp=new List<int>();
It returns a list of employee numbers with single column as below

ID
1
2
3
4
5

To create a list with multiple columns, it would be the better approach to create a List which stores a class with multiple properties.

Let us suppose we have to return employee information with multiple columns  as below







IDNameAddressPhone
1RamaHyd123456
2SureshSec545544
3VenkatWarangal989889
4MaheshDelhi454545


We need to create a list which returns a list employee information as below
using System;
using System.Collections.Generic;


public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int Phone { get; set; }
}

public class Employeeinformation
{
public void GetEmployeeInformation()
{
List<Employee> lstEmp = new List<Employee>();
Program lc = new Program();
lstEmp.Add(new Employee { ID = 1, Name = "Rama", Address = "Hyd", Phone = 12346 });
lstEmp.Add(new Employee { ID = 2, Name = "Suresh", Address = "Sec", Phone = 545544 });
lstEmp.Add(new Employee { ID = 3, Name = "Venkat", Address = "Warangal", Phone = 989889 });
lstEmp.Add(new Employee { ID = 4, Name = "Mahesh", Address = "Delhi", Phone = 454545});
lc.employee(lstEmp);
}
}

public class Program
{
public void employee(List<Employee> emp)
{
foreach (var item in emp)
{
Console.WriteLine("ID={0},Name={1},Address={2},Phone={3}", item.ID, item.Name, item.Address, item.Phone);
}
}
public static void Main()
{
Employeeinformation einfo = new Employeeinformation();
einfo.GetEmployeeInformation();
}
}


The above code results as below
ID=1,Name=Rama,Address=Hyd,Phone=12346
ID=2,Name=Suresh,Address=Sec,Phone=545544
ID=3,Name=Venkat,Address=Warangal,Phone=989889
ID=4,Name=Mahesh,Address=Delhi,Phone=454545

Practice

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.