MST
星途 面试题库

面试题:Visual Basic中LINQ查询表达式基础应用

假设有一个整数数组`Dim numbers() As Integer = {1, 2, 3, 4, 5, 6}`,请使用Visual Basic的LINQ查询表达式找出数组中所有偶数,并将其以新数组的形式返回。
13.6万 热度难度
编程语言Visual Basic

知识考点

AI 面试

面试题答案

一键面试
Imports System.Linq

Module Module1
    Sub Main()
        Dim numbers() As Integer = {1, 2, 3, 4, 5, 6}
        Dim evenNumbers = From num In numbers Where num Mod 2 = 0 Select num.ToArray()
        For Each num In evenNumbers
            Console.WriteLine(num)
        Next
        Console.ReadKey()
    End Sub
End Module

上述代码中:

  1. Imports System.Linq 引入LINQ命名空间。
  2. Main 方法中,定义了整数数组 numbers
  3. 使用LINQ查询表达式 From num In numbers Where num Mod 2 = 0 Select num 筛选出所有偶数,最后通过 ToArray() 方法将结果转换为新的数组 evenNumbers
  4. 最后通过 For Each 循环遍历并输出新数组中的元素。