Cursor

mode

Language Support

Drag

Support center +9-587-325-902

Get in touch

Awesome Image Awesome Image

Blog March 10, 2024

Practice LINQ Part 2

Writen by to.sandeep.2005

comments 0

11. Describe the problem/question

Problem: Implement a LINQ query to calculate the moving average of a sequence of numbers over a specified window size. The moving average should be computed for each element in the sequence based on the element itself and the preceding elements up to the window size. For example, for a window size of 3 and a sequence [2, 3, 5, 8, 13], the moving averages would be [2, 2.5, 3.33, 5.33, 8.67].

Solution in C# with Data

First, let’s define our sequence of numbers:

This LINQ query operates in two steps:

  1. It projects each number in the sequence to an anonymous type containing the number and its index.
  2. For each element, it computes the moving average by skipping elements before the current window (using Math.Max(0, n.Index - windowSize + 1) to ensure the skip count never goes negative), taking up to windowSize elements, and then calculating the average.

This approach efficiently calculates the moving average for each element in the sequence, respecting the specified window size and handling cases where the window extends beyond the start of the sequence.

12. Describe the problem/question

Problem: From a collection of orders, each represented by an Order object that includes properties for ID, CustomerID, OrderDate, and TotalAmount, identify all customers who have placed more than three orders within a single calendar year. The result should list each qualifying customer’s ID and the year they placed more than three orders.

Solution in C# with Data

This LINQ query groups the orders by both CustomerID and the year extracted from OrderDate. It then filters these groups to identify those with more than three orders, representing customers who placed more than three orders in a single calendar year. Finally, it projects the results to include the CustomerID and the year for each qualifying group. This efficiently identifies and lists customers meeting the criteria.

13. Describe the problem/question

Problem: Implement a LINQ query to find all the prime numbers in a given list of integers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The result should include all the prime numbers from the given list, ordered in ascending order.

Solution in C# with Data

In this solution, the IsPrime method checks each number to determine if it’s a prime number. The LINQ query then filters the list of integers, keeping only those that are prime according to the IsPrime method. The query also orders the resulting prime numbers in ascending order before converting them to a list, which is then iterated over to display each prime number.

14. Describe the problem/question

Problem: Given a list of students where each student is represented by a Student object that includes properties for ID, Name, and a collection of Scores (a list of integers representing test scores), write a LINQ query to find students who have an average score above 85. Additionally, for each qualifying student, calculate their average score and order the results by the average score in descending order. The result should include the student’s name and their average score.

Solution in C# with Data

This LINQ query first projects each student into an anonymous type including the student’s name and their average score. It then filters this list to include only those students whose average score is greater than 85. Finally, it orders the resulting list by the average score in descending order. The final list of students is then printed out, displaying the name and average score of each high-scoring student.

15. Describe the problem/question

Problem: Given a collection of books, each represented by a Book object that includes properties for ID, Title, Author, PublishedYear, and Genres (a list of strings representing genres), perform a multi-level analysis to:

  1. Identify the most common genre across all books.
  2. For the most common genre, find the author(s) who have published the most books in that genre.
  3. Within this genre, for each author identified in step 2, calculate the average publication year of their books, rounding down to the nearest year.

Solution in C# with Data

This solution involves several LINQ queries to incrementally solve the problem:

  1. Most Common Genre: Combines all genres from all books, groups them by genre, and selects the genre with the highest count.
  2. Top Authors in Genre: Filters books by the most common genre, groups them by author, and finds the author(s) with the highest count of books in that genre.
  3. Average Publication Year: For each top author identified in the previous step, calculates the average publication year of their books in the most common genre, rounding down to the nearest year.

This approach systematically addresses the multi-level analysis, providing detailed insights based on the given collection of books.

16. Describe the problem/question

Problem: You have a complex dataset of employees, each represented by an Employee object that includes properties for ID, Name, Position, Department, HireDate (of type DateTime), and Salary. Your task is to perform a comprehensive analysis to:

  1. Identify the department with the highest average salary.
  2. Within this department, find the position with the highest average salary.
  3. For the position identified in step 2, list all employees in descending order of their hire date (most recently hired first).

Solution in C# with Data

This comprehensive analysis involves:

  1. Department with the Highest Average Salary: Groups employees by department, calculates the average salary for each, and identifies the department with the highest average.
  2. Position with the Highest Average Salary in That Department: Filters employees by the department identified in step 1, groups by position, calculates the average salary for each position, and identifies the position with the highest average salary.
  3. Employees in the Identified Position: Filters employees by both the department and position identified in the previous steps, and lists them in descending order of their hire date.

This solution showcases a methodical approach to analyzing and extracting insights from complex datasets using LINQ in C#.

17. Describe the problem/question

Problem: Given a list of students and their enrollment records in various courses, where each student is represented by a Student object that includes properties for ID, Name, and a collection of Courses (each course represented by a Course object including properties for CourseID and CourseName), perform an analysis to:

  1. Identify courses with the highest student enrollment.
  2. For the course(s) identified in step 1, list all students enrolled in those courses.
  3. Calculate the total number of unique students across all the highest enrollment courses.

Solution in C# with Data

This solution involves:

  1. Flattening the list of students and their courses to get a comprehensive list of enrollments.
  2. Grouping by CourseID to identify the courses with the highest enrollment based on count.
  3. Filtering students enrolled in the highest enrollment courses, ensuring to list them along with the courses.
  4. Calculating the total number of unique students across all these courses by counting distinct student IDs.

This method provides a thorough analysis of the course enrollments, highlighting courses with high student interest and profiling student participation in these courses.

18. Describe the problem/question

Problem: For a dataset of weather observations where each observation is represented by an Observation object including properties for ID, Location, ObservationDate (of type DateTime), Temperature, and Precipitation, perform an analysis to:

  1. Calculate the average temperature and total precipitation for each location for each month.
  2. Identify the month with the highest average temperature for each location.
  3. For each location, find the month with the highest total precipitation.

Solution in C# with Data

This comprehensive analysis involves:

  1. Grouping observations by location and month to calculate the average temperature and total precipitation for each.
  2. For each location, identifying the month with the highest average temperature.
  3. Similarly, for each location, finding the month with the highest total precipitation.

This approach efficiently processes and aggregates the weather observation data, providing valuable insights into temperature and precipitation trends at different locations.

19. Describe the problem/question

Problem: You have data from an e-commerce platform involving customers, orders, and products. Each Customer is represented by an object with properties for CustomerID, Name, and Country. Each Order includes properties for OrderID, CustomerID, OrderDate, and a list of ProductIDs (representing products ordered). Each Product has ProductID, Name, and Price. Perform an analysis to:

  1. Calculate the total spending per customer.
  2. For each country, find the customer who has spent the most.
  3. Identify the most popular product (the product ordered by the highest number of different customers).

Solution in C# with Data

This solution involves:

  1. Calculating the total spending per customer by aggregating order details and product prices.
  2. Determining the top spender in each country by grouping customers based on their country and comparing their total spendings.
  3. Finding the most popular product by counting the number of distinct customers who ordered each product.

These steps require combining data from different sources and performing aggregate computations to extract meaningful insights from the e-commerce dataset.

20. Describe the problem/question

Problem: You have transaction data for an online store where each transaction is represented by a Transaction object including properties for TransactionID, CustomerID, TransactionDate (of type DateTime), and Amount. Perform an analysis to:

  1. Calculate monthly sales totals for the past year.
  2. Identify the month with the highest sales total.
  3. For the month identified in step 2, list all transactions in descending order of amount.

Solution in C# with Data

This solution involves:

  1. Filtering transactions to those within the last year, then grouping by year and month to calculate sales totals.
  2. Sorting these grouped totals to find the month with the highest sales.
  3. Filtering transactions again to find those in the identified month and sorting them by amount.

This approach demonstrates how to use LINQ for temporal data analysis, highlighting the ability to group, sort, and filter datasets based on time and other criteria to derive meaningful insights.

Tags :

Leave A Comment