C# 11 .NET Core in 3 hours with Projects and Source Code

Includes Projects and Theory. More content in less hours - measured words and clear audio.
4.25 (2 reviews)
Udemy
platform
English
language
Programming Languages
category
instructor
C# 11 .NET Core in 3 hours with Projects and Source Code
47
students
5 hours
content
May 2023
last update
$54.99
regular price

Why take this course?

Based on the content you've provided, it seems you're looking for guidance on a variety of C# programming topics, including LINQ joins, EF Core database operations, functional techniques like pattern matching and discards, asynchronous task programming, exception handling, and processing CSV files. Let's break down each topic and provide some insights or examples that could help you understand or practice these concepts.

LINQ Joins

LINQ joins allow you to combine different collections based on a relationship between them. There are several types of joins:

  • Join: Performs an inner join.
  • GroupJoin: Groups all matching elements from the second sequence into groups, along with the elements from the first sequence that have a matching key.
  • DistinctJoin: Joins distinct elements from the first to all elements from the second collection that have a matching key.

Here's an example of how you might perform a GroupJoin in C#:

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

public class Program
{
    public static void Main()
    {
        var categories = new List<Category>
        {
            new Category { Id = 1, Name = "For Men" },
            new Category { Id = 2, Name = "For Women" },
            new Category { Id = 3, Name = "For Kids" }
        };

        var subCategories = new List<SubCategory>
        {
            new SubCategory { Id = 1, CategoryFK = 1, Name = "Shirts" },
            new SubCategory { Id = 2, CategoryFK = 1, Name = "T Shirts" },
            new SubCategory { Id = 3, CategoryFK = 1, Name = "Trousers" },
            new SubCategory { Id = 4, CategoryFK = 2, Name = "Skirts" },
            new SubCategory { Id = 5, CategoryFK = 2, Name = "Shoes" }
        };

        var groupedSubCategories = subCategories
            .GroupJoin(subCategories,
                c => c.Id,
                s => s.CategoryFK,
                (c, s) => new { Category = c.Name, SubCategories = s.SelectMany(s => s.Name) });

        foreach (var group in groupedSubCategories)
        {
            Console.WriteLine($"Category: {group.Category}, SubCategories: {string.Join(", ", group.SubCategories)}");
        }
    }
}

EF Core Database Operations

Entity Framework Core (EF Core) is an object-relational mapper (ORM) that enables .NET developers to work with a database using .NET objects, eliminating the need for most of the data access code that designers of corporate applications usually have to write. Here's a simple example of adding a new SubCategory entity to the database:

using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public DbSet<SubCategory> SubCategories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SubCategory>().HasKey(sc => sc.Id);
        modelBuilder.Entity<SubCategory>().Property(sc => sc.Name).IsRequired();
        // Other configurations...
    }
}

// In your main method or a service class
using (var context = new MyDbContext())
{
    var subCategory = new SubCategory { Name = "Hats", CategoryFK = 1 };
    context.SubCategories.Add(subCategory);
    context.SaveChanges();
}

Functional Techniques (Pattern Matching and Discards)

Pattern matching in C# allows you to inspect values and bind them to variables or discard them if not needed. Here's an example using pattern matching with switches:

object obj = "Hello, World!";
if (obj is string s)
{
    Console.WriteLine($"The string has a length of {s.Length}");
}
else if (obj is int i)
{
    Console.WriteLine(i); // Discard the variable 's' as it's not needed here
}

And here's an example using discards:

(var name, var age) = GetUserData();
// Do something with 'name'
// Discard 'age' if not needed
(_ = age, Console.WriteLine($"User name: {name}"));

Asynchronous Task Programming

Asynchronous programming allows long-running operations to execute without blocking the main thread of execution. Here's an example using async and await:

private static async Task ProcessFileAsync(string filePath)
{
    try
    {
        using (var reader = new StreamReader(filePath))
        {
            string line;
            var records = new List<Record>();

            while ((line = await reader.ReadLineAsync()) != null)
            {
                var parts = line.Split(',');
                if (parts.Length == 2 && int.TryParse(parts[1], out _))
                {
                    records.Add(new Record(parts[0], int.Parse(parts[1])));
                }
                else
                {
                    throw new FormatException("Invalid record format.");
                }
            }

            // Process the records...
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error at record--- {ex.Message}");
    }
}

Exception Handling

Proper exception handling ensures that your application can recover gracefully from errors and provide useful feedback to the user or developer. Here's an example of catch blocks:

try
{
    // Some operation that might fail
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("The file was not found.");
    // Handle the specific exception type
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred.");
    // Handle all other exceptions
}

CSV Processing Project Exercise

For processing a CSV file, you can use streams and LINQ to read the file and then sort and group the data as required. Here's an example of reading a CSV file and outputting the total amount billed:

using System;
using System.IO;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var filePath = "path/to/your/file.csv";
        var totalAmount = 0m;
        var records = new List<Record>();

        using (var reader = new StreamReader(filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                var parts = line.Split(',');
                if (parts.Length == 2 && decimal.TryParse(parts[1], NumberStyles.Currency, null, out decimal amount))
                {
                    records.Add(new Record(parts[0], amount));
                    totalAmount += amount;
                }
            }
        }

        // Sort records by name and output them
        var sortedRecords = records.OrderBy(r => r.Name).ToList();
        foreach (var record in sortedRecords)
        {
            Console.WriteLine($"{record.Name}: ${record.Amount}");
        }

        // Output the total amount billed
        Console.WriteLine($"Total Amount Billed: ${totalAmount:C2}");
    }
}

public class Record
{
    public string Name { get; private set; }
    public decimal Amount { get; private set; }

    public Record(string name, decimal amount)
    {
        Name = name ?? throw new ArgumentNullException(nameof(name));
        Amount = amount;
    }
}

These examples cover the basics of each topic. Depending on your specific use case and requirements, you might need to adjust the code accordingly.

Loading charts...

Related Topics

4921128
udemy ID
10/10/2022
course created date
11/11/2022
course indexed date
Bot
course submited by