AI interviewer: LINQ and Lambda expressions (1)

AI interviewer: LINQ and Lambda expressions (1)

When interviewers face interview questions about LINQ and Lambda expressions in C#, they usually involve the basic concepts, usage, practical application, and comparison with other related technologies of these two topics. Here are some possible interview questions with brief answers and relevant examples and code:

1. What is LINQ? What are its main advantages?

Answer: LINQ (Language Integrated Query) is a query technology integrated in the C# programming language, which allows the use of SQL-like query syntax in the code to query data. The main advantages of LINQ include concise and advanced query syntax, static type safety, smooth and composable query logic, optimized performance, high readability, and client-side processing capabilities.

Example and code: Suppose there is a class containing student information Student, we can use LINQ to query all students whose surname is "Smith":

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

List<Student> students = new List<Student>
{
    
    
    new Student {
    
     Id = 1, Name = "John Smith" },
    new Student {
    
     Id = 2, Name = "Jane Smith" },
    new Student {
    
     Id = 3, Name = "Mike Johnson" }
};

var smithStudents = students.Where(s => s.Name.Contains("Smith"));

foreach (var student in smithStudents)
{
    
    
    Console.WriteLine(student.Name);
}
// Output: John Smith
//         Jane Smith

2. What is a Lambda expression? What does it do in LINQ?

Answer: A lambda expression is an anonymous function that can be used where a function is expected as an argument, or to simplify delegate expressions in your code. In LINQ, Lambda expressions are usually used to specify query conditions, sorting rules, projection operations, etc., making LINQ queries more flexible and concise.

Case and code: Suppose we need to studentsfind students whose age is greater than or equal to 18 in the list, we can use Lambda expression to achieve filtering:

class Student
{
    
    
    public int Id {
    
     get; set; }
    public string Name {
    
     get; set; }
    public int Age {
    
     get; set; }
}

List<Student> students = new List<Student>
{
    
    
    new Student {
    
     Id = 1, Name = "John Smith", Age = 20 },
    new Student {
    
     Id = 2, Name = "Jane Smith", Age = 17 },
    new Student {
    
     Id = 3, Name = "Mike Johnson", Age = 22 }
};

var adults = students.Where(s => s.Age >= 18);

foreach (var student in adults)
{
    
    
    Console.WriteLine(student.Name);
}
// Output: John Smith
//         Mike Johnson

3. In LINQ, what are the commonly used operators? Please list and briefly describe what they do.

Answer: In LINQ, commonly used operators include:

  • Where: Used to filter elements that meet the criteria.
  • Select: Used to project each element in the collection to a new form or type.
  • OrderBy/ OrderByDescending: Used to sort the elements in ascending or descending order according to the specified criteria.
  • GroupBy: Used to group elements based on the specified key.
  • Join: Used to concatenate two collections and match based on the specified key.
  • Aggregate: Used to accumulate or aggregate the elements in the collection.

Case and code: Suppose there is a class containing order information Order, we can use LINQ operators to process order data:

class Order
{
    
    
    public int OrderId {
    
     get; set; }
    public string CustomerName {
    
     get; set; }
    public decimal Amount {
    
     get; set; }
    public DateTime OrderDate {
    
     get; set; }
}

List<Order> orders = new List<Order>
{
    
    
    new Order {
    
     OrderId = 1, CustomerName = "John Smith", Amount = 100.50m, OrderDate = DateTime.Parse("2023-06-01") },
    new Order {
    
     OrderId = 2, CustomerName = "Jane Smith", Amount = 50.25m, OrderDate = DateTime.Parse("2023-06-02") },
    new Order {
    
     OrderId = 3, CustomerName = "Mike Johnson", Amount = 200.00m, OrderDate = DateTime.Parse("2023-06-03") }
};

// Example: 查询订单金额大于100的订单,并按订单日期降序排序
var filteredAndSortedOrders = orders
    .Where(o => o.Amount > 100)
    .OrderByDescending(o => o.OrderDate);

foreach (var order in filteredAndSortedOrders)
{
    
    
    Console.WriteLine($"Order ID: {
      
      order.OrderId}, Customer: {
      
      order.CustomerName}, Amount: {
      
      order.Amount:C}, Order Date: {
      
      order.OrderDate:D}");
}
// Output:
// Order ID: 3, Customer: Mike Johnson, Amount: $200.00, Order Date: June 3, 2023
// Order ID: 1, Customer: John Smith, Amount: $100.50, Order Date: June 1, 2023

4. What are the similarities and differences between LINQ and SQL? What scenarios are they suitable for?

Answer: Both LINQ and SQL are tools for querying data, but they have some differences:

  • LINQ is a query technology integrated in programming languages ​​like C# while SQL is a query language used to interact with databases.
  • LINQ uses a syntax similar to C#, which is more concise and advanced, while SQL uses its own independent syntax.
  • LINQ can catch type errors at compile time and is statically type safe, while SQL can only find errors at runtime.
  • LINQ can run on a variety of data sources while SQL is mainly used for database queries.

Applicable scene:

  • LINQ is suitable for querying, filtering, sorting, grouping and other operations of data collection in code, and provides more flexible composability, suitable for data processing in memory.
  • SQL is suitable for interacting with databases, performing complex database query, update, insert, delete and other operations, suitable for large-scale data storage and processing.

Case and code: Considering that some data filtering and aggregation may be required on the client side in actual development, we can use LINQ to query data first, and then use SQL to update related records in the database according to the results:

// LINQ查询:筛选金额大于100的订单
var filteredOrders = orders.Where(o => o.Amount > 100);

// 使用SQL更新数据库中筛选出的订单状态为"已处理"
using (var dbContext = new YourDbContext())
{
    
    
    foreach (var order in filteredOrders)
    {
    
    
        var dbOrder = dbContext.Orders.FirstOrDefault(o => o.OrderId == order.OrderId);
        if (dbOrder != null)
        {
    
    
            dbOrder.Status = "已处理";
        }
    }
    dbContext.SaveChanges();
}

5. What is Deferred Execution when using LINQ? What good is it?

Answer: Deferred execution means that the LINQ query is not executed immediately, but remains unexecuted until the query results are accessed. It gets executed when you need to actually use the query results.

benefit:

  • Resource saving: If the query is not used, computing resources will not be wasted executing useless queries.
  • Optimizing performance: LINQ provides the opportunity to optimize queries by combining multiple operations into a single query, thereby reducing the number of accesses to the data source.

Example and Code: Consider a situation where a query may return a large amount of data, but we only need to display the first few results. In this case, lazy execution can help us avoid loading a lot of data at once:

// 查询金额大于100的订单,但只显示前5个结果
var filteredOrders = orders.Where(o => o.Amount > 100).Take(5);

// 实际使用查询结果时,它会被执行
foreach (var order in filteredOrders)
{
    
    
    Console.WriteLine($"Order ID: {
      
      order.OrderId}, Amount: {
      
      order.Amount:C}");
}

Please note that the above interview questions and answers are for reference only, and may be adjusted and discussed in depth during the actual interview according to specific circumstances. During the interview, in addition to answering questions, you can also provide more application scenarios and specific code examples about LINQ and Lambda expressions in combination with actual project experience to highlight the candidate's skills and experience.

おすすめ

転載: blog.csdn.net/qq_36799389/article/details/131904211