In my
previous post I was showing how to implement one to many relation ship with two
class. But situation may heppain that we have to implement one to many
relationship within same class member.
Say, I
have a person class and one person may prefer to add more than one location as
there preferred location. Then how we will implement that ? Have a look on
below code.
Here I
have implemented person class and have created one generic list of string type.
Within constructor I am populating the list(you can also populate list
dynamically by passing argument through constructor) . And when we are creating
object of person class automatically preferref location list is getting
populated for that object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
namespace BlogProject
{
public class Person
{
public string Name {get;set;}
List<String>
LocList = null;
public Person()
{
LocList = new List<string>();
LocList.Add("kolkata");
LocList.Add("Bangalore");
}
public void
ShowData()
{
Console.Write("Name:-
" + Name+ "\n");
Console.Write("Preffered
Location:-");
foreach (var v in LocList)
{
Console.Write(v.ToString() + " ,");
}
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Name = "Sourav";
p.ShowData();
Console.ReadLine();
}
}
}
And the output is:-
No comments:
Post a Comment