C# Keywords Tutorial Part 10: by

C# Keywords Tutorial Part 10: by

When it comes to grouping and sorting data as well as LINQ queries, the C# language’s “by” keyword is an important tool. We’ll examine the “by” keyword in C# and demonstrate its use in various contexts in this blog post.

Grouping Data

Data grouping is one of the most popular uses of the “by” keyword. The “by” keyword is frequently used in LINQ queries to arrange data according to a certain criterion. Here’s an illustration:

var orders = new[] {
    new { Name = "Alice", Product = "Book", Price = 10 },
    new { Name = "Bob", Product = "Book", Price = 12 },
    new { Name = "Charlie", Product = "CD", Price = 8 },
    new { Name = "David", Product = "CD", Price = 9 },
    new { Name = "Eve", Product = "DVD", Price = 15 }
};

var groupedOrders = from order in orders
                    group order by order.Product;

foreach (var group in groupedOrders)
{
    Console.WriteLine("Product: {0}", group.Key);
    foreach (var order in group)
    {
        Console.WriteLine("   Name: {0}, Price: {1}", order.Name, order.Price);
    }
}

In this example, we have an array of orders, each with a name, product, and price. We use the “by” keyword to group the orders by product, and then we use a nested loop to iterate over each group and output the orders for that product. The output of the code will be:

Product: Book
   Name: Alice, Price: 10
   Name: Bob, Price: 12
Product: CD
   Name: Charlie, Price: 8
   Name: David, Price: 9
Product: DVD
   Name: Eve, Price: 15

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *