DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Partitioning Data with a Dictionary in C#

Partitioning data using a dictionary in C# is a versatile technique that enables you to group and organize related data logically. This approach is particularly useful when you need to efficiently retrieve or process subsets of data based on specific criteria, such as grouping students by grade or products by category.

In this article, we’ll explore how to partition data with a dictionary using a complete, step-by-step example of grouping students by grade.


Why Use a Dictionary for Partitioning?

A dictionary is an excellent choice for partitioning data because:

  1. Logical Grouping: It allows you to logically group related data by key.
  2. Fast Lookup: You can retrieve data for a specific key with an average time complexity of O(1).
  3. Flexible Values: The value associated with each key can be any type of collection, such as a list, array, or even another dictionary.

Scenario: Grouping Students by Grade

Imagine you’re building a school management system. You need to organize students by grade and display information about each grade efficiently. Using a dictionary, you can group students logically and retrieve their data quickly.


Step 1: Define the Data Structure

We’ll start by defining a Student class to represent individual students:

public class Student
{
    public string Name { get; set; }
    public double GPA { get; set; }

    public Student(string name, double gpa)
    {
        Name = name;
        GPA = gpa;
    }
}
Enter fullscreen mode Exit fullscreen mode

The Student class includes:

  • A Name property for the student’s name.
  • A GPA property for the student’s grade point average.

Step 2: Create and Populate the Dictionary

Next, we’ll create a dictionary to group students by their grade. The dictionary’s key will be a string (e.g., "Grade 9"), and the value will be a list of Student objects.

Dictionary<string, List<Student>> studentsByGrade = new Dictionary<string, List<Student>>();

// Populate the dictionary with data
studentsByGrade["Grade 9"] = new List<Student>
{
    new Student("Alice", 3.8),
    new Student("Bob", 3.5),
    new Student("Charlie", 3.9)
};

studentsByGrade["Grade 10"] = new List<Student>
{
    new Student("David", 3.4),
    new Student("Ella", 3.6),
    new Student("Frank", 3.7)
};

studentsByGrade["Grade 11"] = new List<Student>
{
    new Student("Grace", 3.9),
    new Student("Hank", 3.3),
    new Student("Isabella", 3.5)
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Retrieve and Display Data

To display students in a specific grade, we use the TryGetValue method for safe dictionary access. Additionally, we can sort the students by GPA before displaying them.

string grade = "Grade 10";

if (studentsByGrade.TryGetValue(grade, out List<Student> students))
{
    Console.WriteLine($"Students in {grade}:");
    foreach (var student in students.OrderByDescending(s => s.GPA))
    {
        Console.WriteLine($"{student.Name}: GPA {student.GPA:F1}");
    }
}
else
{
    Console.WriteLine($"No data found for {grade}");
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Dynamically Update the Data

You can also dynamically add new students to an existing grade or create a new grade.

Adding a New Student:

studentsByGrade["Grade 9"].Add(new Student("Jack", 3.6));
Enter fullscreen mode Exit fullscreen mode

Adding a New Grade:

studentsByGrade["Grade 12"] = new List<Student>
{
    new Student("Kevin", 4.0),
    new Student("Laura", 3.8)
};
Enter fullscreen mode Exit fullscreen mode

Complete Code Example

Here’s the full program combining all the steps:

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

namespace PartitioningDataWithDictionary
{
    public class Student
    {
        public string Name { get; set; }
        public double GPA { get; set; }

        public Student(string name, double gpa)
        {
            Name = name;
            GPA = gpa;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, List<Student>> studentsByGrade = new Dictionary<string, List<Student>>();

            studentsByGrade["Grade 9"] = new List<Student>
            {
                new Student("Alice", 3.8),
                new Student("Bob", 3.5),
                new Student("Charlie", 3.9)
            };

            studentsByGrade["Grade 10"] = new List<Student>
            {
                new Student("David", 3.4),
                new Student("Ella", 3.6),
                new Student("Frank", 3.7)
            };

            studentsByGrade["Grade 11"] = new List<Student>
            {
                new Student("Grace", 3.9),
                new Student("Hank", 3.3),
                new Student("Isabella", 3.5)
            };

            string grade = "Grade 10";
            if (studentsByGrade.TryGetValue(grade, out List<Student> students))
            {
                Console.WriteLine($"Students in {grade}:");
                foreach (var student in students.OrderByDescending(s => s.GPA))
                {
                    Console.WriteLine($"{student.Name}: GPA {student.GPA:F1}");
                }
            }

            Console.WriteLine("\nAdding a New Student to Grade 9:");
            studentsByGrade["Grade 9"].Add(new Student("Jack", 3.6));

            foreach (var student in studentsByGrade["Grade 9"].OrderByDescending(s => s.GPA))
            {
                Console.WriteLine($"{student.Name} - GPA: {student.GPA:F1}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Sample Output

Students in Grade 10:
Frank: GPA 3.7
Ella: GPA 3.6
David: GPA 3.4

Adding a New Student to Grade 9:
Charlie - GPA: 3.9
Alice - GPA: 3.8
Jack - GPA: 3.6
Bob - GPA: 3.5
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Partitioning: Grouping data using a dictionary makes it easy to manage subsets of data.
  • Dynamic Updates: Adding new data to existing groups or creating new groups is straightforward.
  • Efficiency: Dictionaries provide fast lookups, making them ideal for partitioning large datasets.

Top comments (0)