Menu

Wednesday, 18 December 2024

UUID v7 in .NET 9

 

About


.NET 9 comes up with so many excited features as discussed in earlier posts. This post, we are focusing on UUID v7 feature.
Please refer the following links for other .NET 9 LINQ features

The earlier versions of .NET, we've used Guid.NewGuid() (version 4) method generate UUIDs. It simply generates unique identifier which being used in our projects.

The present .NET 9 version supports UUID v7 format of code like Guid.CreateVersion7(). This generated UUID incorporated timestamp already in it. So, This is really very helpful when we stored this UUID in database level to Sort it  based on creation time.

The structure of UUID format is as follows.

 48-bit timestamp || 12-bit random ||    62-bit random

48-bit timestamp: It represents the number of milliseconds since Unix epoch. so, It provides info about creation time.
12-bit random: It adds randomness to ensure uniqueness in within same millisecond.
62-bit random: It also ensures overall uniqueness by offering randomness of entropy.

Code Examples

Before .NET 9

var guid = Guid.NewGuid(); // v4 UUID

.NET 9

var guidv7 = Guid.CreateVersion7(); // v7 UUID
var guidv7 = Guid.CreateVersion7(); // v7 UUID
This by default inherits UtcNow timeformat.

Lets explore about Sort feature by creating multiple UUIDs custom way.

//Just added the guid by adding different time provider by add/subtract minutes to current Utc time.

var guidList = new List
{
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow()),
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow().AddMinutes(-10)),
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow().AddMinutes(10)),
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow().AddMinutes(-20))

};
//write the guids in whatever list contains.
foreach (var v7guid in guidList)
{
    Console.WriteLine(v7guid.ToString());
}

Console.WriteLine("=====================");
//Order the guidlist and then write list.
//The result you can identify guids are ordered based on creation time.
var sortedList = guidList.OrderBy(x => x).ToList();
foreach (var v7guid in sortedList)
{
    Console.WriteLine(v7guid.ToString());
}

Screenshots









Summary


We have explored UUID v7 feature in .NET 9and its advantages of inbuilt timestamp which can be really helpful to order created UUIDs in database level. So, lets start use in our project and get benefitted.

Stay tuned for more articles. Thanks for reading!!



Monday, 16 December 2024

.NET 9 Index in LINQ

 

About


Index is one of feature introduced in .NET LINQ. By using this method, we can easily extract implicit index of IEnumerable.

The other .NET 9 LINQ features are as follows.

The Index method returns index and index of an item in following format.

Format: IEnumerable<(int Index, TSource Item)>

Scenario


Lets consider to display employee name in list and their respective order.

Employee class

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}


Setup Employee List with Sample Data


  var employees = new List<Employee> {
  new Employee(){ Id = 11, Name = "Ram" },
  new Employee(){ Id = 12, Name = "Bheem" },
  new Employee(){Id = 13, Name = "Lakshman"},
  new Employee(){Id = 14, Name = "Hanu"},
  new Employee(){Id = 15, Name = "Dev"},
  new Employee(){Id = 16, Name = "Nandan"},
  new Employee(){Id = 17, Name = "Krish"},
  new Employee(){Id = 18, Name = "Hash"},
};

  foreach ((int index, Employee emp) in employees.Index())
  {
      Console.WriteLine($"Index: {index}, Employee Name: {emp.Name}");
  }


Screenshots


The following code and output screenshots gives easy understanding and for your implementation.

Code



Output



Summary



This post explored about Index feature in LINQ introduced in .NET9.
Thanks for reading this and stay tuned for more articles.

Sunday, 15 December 2024

.NET 9 AggregateBy LINQ

 About


In this post, we are exploring about AggregateBy LINQ method introduced in .NET 9. This is very helpful and being used in scenarios of aggregate operations such as sum, average and grouping of data based on custom conditions.

In Earlier post, Please look into about other feature discussed about CountBy in LINQ 9

So, Lets go ahead to discuss/understand about AggregateBy in LINQ.

Scenario


Lets consider following scenario and understand implementation of this before and after .NET 9 approach.

"Get sum of employee merit score points based on job level"

Employee class

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int YearJoin { get; set; }
    public int JobLevel { get; set; }
    public int MeritPoints { get; set; }
}


Setup Employee List with Sample Data

  var employees = new List<Employee> {
  new Employee(){ Id = 11, Name = "Ram", YearJoin = 2015, JobLevel = 6, MeritPoints = 10 },
  new Employee(){ Id = 12, Name = "Bheem", YearJoin = 2012, JobLevel = 5, MeritPoints = 20 },
  new Employee(){Id = 13, Name = "Lakshman", YearJoin = 2015, JobLevel = 6, MeritPoints = 30},
  new Employee(){Id = 14, Name = "Hanu", YearJoin = 2016, JobLevel = 6, MeritPoints = 40},
  new Employee(){Id = 15, Name = "Dev", YearJoin = 2024, JobLevel = 6, MeritPoints = 50},
  new Employee(){Id = 16, Name = "Nandan", YearJoin = 2012, JobLevel = 5, MeritPoints = 60},
  new Employee(){Id = 17, Name = "Krish", YearJoin = 2012, JobLevel = 5, MeritPoints = 70},
  new Employee(){Id = 18, Name = "Hash", YearJoin = 2015, JobLevel = 6, MeritPoints = 80},
};


Before .NET 9


//BEFORE .NET 9 Example
// Aggregate MeritPoints by Job Level using GroupBy and Aggregate
var meritPointsByEmpJobLevel = employees
    .GroupBy(user => user.JobLevel) // Group users by their Job Level
    .Select(group => new
    {
        JobLevel = group.Key,
        TotalMeritPoints = group.Sum(user => user.MeritPoints)
    }
            ); // Aggregate Merit Points for each Job Level
// Print the results
foreach (var jobLevelAggregate in meritPointsByEmpJobLevel)
{
    Console.WriteLine($"Total merit points per each employee level " +
        $"{jobLevelAggregate.JobLevel} is {jobLevelAggregate.TotalMeritPoints}");
}

Aforesaid code example, we did the following steps.
1. Group the employees based on Job level.
2. Select the Job level as Key and Sum of Meri points on respective job level.
3. Display the results in fore ach loop based on select results.

.NET 9


var totalEmpMeritPointsByLevel = employees.AggregateBy(e => e.JobLevel, 
                                    seed: 0, (acc, meritPoints) => acc + meritPoints.MeritPoints);
foreach (var meritPointByLevel in totalEmpMeritPointsByLevel)
{
    Console.WriteLine($"Total merit points per each employee level " +
        $"{meritPointByLevel.Key} is {meritPointByLevel.Value}");
}

The aforesaid .NET 9 code example, we achieved all in one go with AggregateBy example. The code also very clean and crsip.

Syntax:

IEnumerable<(TKey Key, TAccumulate Aggregate)> AggregateBy<TSource, TKey, TAccumulate>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TAccumulate> seedFactory,
    Func<TAccumulate, TSource, TAccumulate> aggregator
);

Screenshots

Code



Output


Summary


In this post, we explored about AggregateBy LINQ feature with ease of use and code examples. Those are really helpful to improve developer productivity and ease of understanding and performance of applications.
Thanks for reading and Stay tuned for more articles!!


Tuesday, 10 December 2024

.NET 9 CountBy LINQ


Introduction

.NET 9 is the latest version of Microsoft's released in Nov 2024. Its open-source development platform for building applications for web, mobile, desktop and cloud environments. 

This release is pack of many new features, LINQ methods and performance improvements and many more.

About

In this post, we are focusing about one of new LINQ method introduced in .NET 9. Its very useful, comprehensive and easily can understand and can be used in our project as well :).

So, Lets start explore on this.

Scenario

Lets consider a easy scenario as "To get employees count based on the year joined".

Employee Class:

public class Employee

{

    public int Id { get; set; }

    public string Name { get; set; }

    public int YearJoin { get; set; }

}

Setup Employee List with Sample Data

  var employees = new List<Employee> {

  new Employee(){ Id = 11, Name = "Ram", YearJoin = 2015 },

  new Employee(){ Id = 12, Name = "Bheem", YearJoin = 2012 },

  new Employee(){ Id = 13, Name = "Lakshman", YearJoin = 2015 },

  new Employee(){ Id = 14, Name = "Hanu", YearJoin = 2016 },

  new Employee(){ Id = 15, Name = "Dev", YearJoin = 2024 },

  new Employee(){ Id = 16, Name = "Nandan", YearJoin = 2012 },

  new Employee(){ Id = 17, Name = "Krish", YearJoin = 2012 },

  new Employee(){ Id = 18, Name = "Hash", YearJoin = 2015 },

};

So, First let us understand - How we are doing currently (Earlier to .NET 9).

Before .NET 9

Approach is - Grouping and Counting

1. GroupBy: Groups the employees based on their value provided (Year).

2. Select(g => new {Key = g.Key, Value = g.Count()}}: project each group into anonymous object with two properties.

  • Key: The year joined.
  • Value: The count of occurrences of employees in the group.
Sample Code:

var empOccurences = employees

                .GroupBy(c => c.YearJoin)
                .Select(g => new { g.Key, Value = g.Count() });

foreach (var empInfo in empOccurences)
{
    Console.WriteLine($"There are {empInfo.Value} users with the year joined {empInfo.Key}");
}

.NET 9

In .NET 9 -Its simplifies the process and streamlined code like below.

foreach (var empCount in employees.CountBy(user => user.YearJoin))
{
    Console.WriteLine($"There are {empInfo.Value} users with the year joined {empInfo.Key}");
}

Screenshots
Code



Output



CountBy Benefits

  • Simplifies the code hence it improves readability and developer productivity.
  • Optimizes the performance by streamlining the grouping and counting process.
  • It makes data aggregation makes more efficient and concise. 

I will come up with another LINQ method introduced in .NET 9 in upcoming post. Stay tuned!!

Thanks for your reading and provide your comments and suggestions as always.