Practical Data Manipulation Techniques in C#

Hello and welcome! Today, we're exploring practical data manipulation techniques in C#. We'll use C# lists to represent our data stream and perform projection, filtering, and aggregation. And here's the star of the show: our operations will be neatly packaged within a C# class! No mess, all clean code.

Introduction to Data Manipulation

Data manipulation is akin to being a sculptor but for data. We chisel and shape our data to get the desired structure. C# lists are perfect for this, and our operations will be conveniently bundled inside a C# class. So, let's get our toolbox ready! Here's a simple C# class, DataStream, that will serve as our toolbox:

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

public class DataStream<T>
{
    public List<T> Data { get; set; }

    public DataStream(List<T> data)
    {
        Data = data;
    }
}
Data Projection in Practice

Our first stop is data projection. Think of it like capturing a photo of our desired features. Suppose we have data about people. If we're only interested in names and ages, we project our data to include just these details. We'll extend our DataStream class with a ProjectData method for this:

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

public class DataStream<T>
{
    public List<T> Data { get; set; }

    public DataStream(List<T> data)
    {
        Data = data;
    }

    public List<dynamic> ProjectData(List<string> keys)
    {
        var projectedData = Data.Select(d =>
        {
            var newObj = new Dictionary<string, object>();
            foreach (var key in keys)
            {
                var propertyInfo = d.GetType().GetProperty(key);
                newObj[key] = propertyInfo?.GetValue(d, null);
            }
            return (dynamic)newObj;
        }).ToList();

        return projectedData;
    }
}

public class Program
{
    public static void Main()
    {
        var ds = new DataStream<dynamic>(new List<dynamic>
        {
            new { Name = "Alice", Age = 25, Profession = "Engineer" },
            new { Name = "Bob", Age = 30, Profession = "Doctor" },
        });

        var projectedDs = ds.ProjectData(new List<string> { "Name", "Age" });
        foreach (var item in projectedDs)
        {
            Console.WriteLine($"{item["Name"]}, {item["Age"]}");
        }
        // Outputs: 
        // Alice, 25
        // Bob, 30
    }
}

As you can see, we now have a new list with just the names and ages!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal