使用 LINQ 打印姓名少于 4 个字符的员工的 C# 程序
LINQ 被称为语言集成查询,它是在 .NET 3.5 中引入的。它使 .NET 语言能够生成查询以从数据源中检索数据。它消除了编程语言和数据库之间的不匹配,并且无论使用哪种类型的数据源,用于创建查询的语法都是相同的。在本文中,我们将研究如何显示那些姓名中包含少于四个字符的员工姓名。所以对于这个任务,我们使用 Where()函数。此函数根据给定条件过滤给定数组。
句法:
data.Where(employee => employee.Length < 4)
例子:
Input : [("m"),("srav"),("a"),("gopi"),("bai")("sai")]
Output : [("m"),("a"),("bai"),("sai")]
Input : [("bobby"),("ramya"),("sairam")]
Output : No Output
方法
To print the list of employees whose name contains less than 4 characters follow the following steps:
- Create a list(i.e., XEmployee) that will contain the name of the employees.
- Add the employee names to the list.
- Now find the employee names whose length is less than 4 characters by using data.Where(employee => employee.Length < 4).
- Display the employee names.
例子:
C#
// C# program display those employee's name
// that contains less than 4 characters in their name
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
static void Main(string[] args)
{
// Define a list
List XEmployee = new List();
// Add names into the list
XEmployee.Add("m");
XEmployee.Add("srav");
XEmployee.Add("a");
XEmployee.Add("gopi");
XEmployee.Add("bai");
XEmployee.Add("sai");
// Choose the employee whose name length is
// less than 4 letters
IEnumerable result = XEmployee.Where(
employee => employee.Length < 4);
Console.WriteLine("Name of the Employees are: ");
// Display employee names
foreach (string stname in result)
{
Console.WriteLine(stname);
}
}
}
输出:
Name of the Employees are:
m
a
bai
sai