In previous articles, we saw how to implement various relationships among C# classes. You can read them here:
- One one relationship in C# class
- Implement one too many relationships in C# class.
- Many to One Relationship in C# Class
In 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 < Matches > MLst = new List < Matches > ();
- List < Cricketer > CList = new List < Cricketer > ();
-
- public string Name { get;
- set; }
-
- public List < Matches > getSetMatch {
- get { return MLst; }
- set { MLst = value; }
- }
-
- public List < Cricketer > 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 < Cricketer > Lst = new List < Cricketer > ();
- 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 < Cricketer > CList = new List < Cricketer > ();
- List < Matches > MList = new List < Matches > ();
-
- Cricketer c = new Cricketer();
- c.Name = "Sourav Ganguly";
- CList.Add(c);
- c = new Cricketer();
- c.Name = "Sachin Tendulkar";
- CList.Add(c);
-
-
- Matches m = new Matches();
- m.MatchVs = "India-Sri Lanka";
- MList.Add(m);
-
-
- m = new Matches();
- m.MatchVs = "India - Bangladesh";
- MList.Add(m);
-
- c.getsetCricketer = CList;
- c.getSetMatch = MList;
- c.Print();
-
- Console.ReadLine();
- }
- }
- }
Here is a sample output:
Conclusion
In this article, we have learned how to implement a Many-To-Many relationship in a C# Class. Hope you have understood the concept. Though it is a very rare scenario where a Many-To-Many relationship is relevant. Happy learning.