.NET Data Manipulation

This section covers essential techniques and best practices for manipulating data within the .NET ecosystem. From querying in-memory collections to interacting with external data sources, we explore powerful tools and libraries.

Language Integrated Query (LINQ)

LINQ provides a powerful and flexible way to query data directly within your .NET code. It integrates query capabilities into C# and Visual Basic, allowing you to work with data from various sources (objects, databases, XML) in a uniform manner.

Key LINQ Features:

Example: LINQ to Objects

Filtering and projecting a list of products:


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

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var products = new List
        {
            new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
            new Product { Id = 2, Name = "Mouse", Price = 25.00m },
            new Product { Id = 3, Name = "Keyboard", Price = 75.00m },
            new Product { Id = 4, Name = "Monitor", Price = 300.00m }
        };

        // Query syntax
        var expensiveProductsQuery = from p in products
                                     where p.Price > 100m
                                     orderby p.Price descending
                                     select new { p.Name, p.Price };

        Console.WriteLine("Expensive Products (Query Syntax):");
        foreach (var item in expensiveProductsQuery)
        {
            Console.WriteLine($"- {item.Name}: ${item.Price}");
        }

        // Method syntax
        var affordableProductsMethod = products
            .Where(p => p.Price <= 100m)
            .OrderBy(p => p.Name)
            .Select(p => p.Name);

        Console.WriteLine("\nAffordable Product Names (Method Syntax):");
        foreach (var name in affordableProductsMethod)
        {
            Console.WriteLine($"- {name}");
        }
    }
}
                

Working with Collections

The .NET Framework provides a rich set of collection types in the System.Collections.Generic namespace. These are fundamental for storing and managing groups of objects.

Common Collection Types:

Collections are often the primary target for LINQ queries, making data manipulation efficient and expressive.

Database Access

.NET offers robust support for interacting with various databases. The primary technologies include ADO.NET and Entity Framework Core.

ADO.NET:

A set of .NET classes for accessing data sources like relational databases. It provides low-level control over data access operations.

Entity Framework Core (EF Core):

A modern, open-source, cross-platform Object-Relational Mapper (ORM) for .NET. It simplifies database access by allowing you to work with data as .NET objects.

Example: EF Core Basic Usage

Retrieving data using EF Core:


using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Replace with your actual connection string
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }
}

public class BlogRepository
{
    public List<Blog> GetAllBlogs()
    {
        using (var context = new BloggingContext())
        {
            return context.Blogs.Include(b => b.Posts).ToList();
        }
    }

    public Blog GetBlogByUrl(string url)
    {
        using (var context = new BloggingContext())
        {
            return context.Blogs.FirstOrDefault(b => b.Url == url);
        }
    }
}
                

Data Serialization

Serialization is the process of converting an object into a format that can be stored or transmitted (e.g., JSON, XML, binary) and then reconstructed later. .NET provides built-in support for this.

Common Serialization Technologies:

Example: Using System.Text.Json

Serializing and deserializing a C# object to/from JSON:


using System;
using System.Text.Json;

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

public class SerializationExample
{
    public static void Main(string[] args)
    {
        var user = new User { Id = 101, Name = "Alice Smith", Email = "alice@example.com" };

        // Serialize to JSON
        string jsonString = JsonSerializer.Serialize(user);
        Console.WriteLine("Serialized JSON:");
        Console.WriteLine(jsonString);

        // Deserialize from JSON
        User deserializedUser = JsonSerializer.Deserialize<User>(jsonString);
        Console.WriteLine("\nDeserialized User:");
        Console.WriteLine($"ID: {deserializedUser.Id}, Name: {deserializedUser.Name}, Email: {deserializedUser.Email}");
    }
}