LINQ examples


LINQ (Language Integrated Query) in C# is incredibly powerful and versatile, especially in scenarios where you need to perform complex data manipulations or queries. Here are five examples showcasing the benefits of using LINQ in such scenarios:

 

Filtering and Transformation:

var filteredAndTransformedData = from item in collection
                                 where item.Condition1 && item.Condition2
                                 select new {
                                     TransformedProperty = item.Property1 + item.Property2,
                                     FilteredProperty = item.Property3
                                 };

Grouping and Aggregation:

var groupedAndAggregatedData = from item in collection
                               group item by item.Category into groupedItems
                               select new {
                                   Category = groupedItems.Key,
                                   TotalQuantity = groupedItems.Sum(x => x.Quantity),
                                   AveragePrice = groupedItems.Average(x => x.Price)
                               };

Joining Multiple Data Sources:

var joinedData = from item1 in collection1
                 join item2 in collection2 on item1.Key equals item2.Key
                 select new {
                     Property1 = item1.Property,
                     Property2 = item2.Property
                 };

Complex Sorting:

var sortedData = from item in collection
                 orderby item.Property1 descending, item.Property2 ascending
                 select item;

Combining Multiple Operations:

var combinedOperations = collection
    .Where(item => item.Condition)
    .OrderBy(item => item.Property)
    .Select(item => new {
        TransformedProperty = item.Property * 2,
        FilteredProperty = item.Property > 10
    });

 

 

 


No files yet, migration hasn't completed yet!