This post has already been read 2279 times!

indexIn this article we will see how to implement a Many-To-Many relationship in a C# class. Let's explain a few scenarios where a Many-To-Many relationship is relevant.

The relationship between a Cricket match and Cricketer is one example of a Many-To-Many relationship. One Cricket match is played by many Cricketers and one Cricketer takes part in many Cricket matches.

Let's implement this example using a C# class.

Relationship between Cricketer and matches

As we have explained many Cricketers play in a single Cricket match and one Cricketer takes part in multiple matches. For the sake of simplicity we have used only a Cricketer class. We can use a Matches class in the same fashion. Have a look at the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Client
{
    class Cricketer
    {
        List MLst = new List();
        List CList = new List();

        public string Name { get; set; }

        public List getSetMatch
        {
            get { return MLst; }
            set { MLst = value; }
        }

        public List getsetCricketer
        {
            get { return CList; }
            set { CList = value; }
        }

        public void Print()
        {
            Console.WriteLine("-----Cricketer Name---- ");
            foreach (Cricketer c in CList)
            {
                Console.WriteLine(c.Name);
            } 

            Console.WriteLine("-----Matches Played----");

            foreach (Matches m in MLst)
            {
                Console.WriteLine(m.MatchVs);
            }
        }
    }

    class Matches
    {
        List Lst = new List();
        public string MatchVs { get; set; }

        public void Print()
        {
            Console.WriteLine("Match Verses");
            foreach (Cricketer c in Lst)
            {
                Console.WriteLine("Cricketer Name:- " + c.Name);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List CList = new List();
            List MList = new List();

            Cricketer c = new Cricketer();
            c.Name = "Sourav Ganguly";
            CList.Add(c);
            c = new Cricketer();
            c.Name = "Sachin Tendulkar";
            CList.Add(c);

            //Add matches
            Matches m = new Matches();
            m.MatchVs = "India-Sri Lanka";
            MList.Add(m);

            //Add another match
            m = new Matches();
            m.MatchVs = "India - Bangladesh";
            MList.Add(m); 
            c.getsetCricketer = CList;
            c.getSetMatch = MList;
            c.Print();

            Console.ReadLine();
        }
    }
}

Comments are closed.

Post Navigation