演示在 LINQ 中将方法用作条件的 C# 程序
LINQ 被称为语言集成查询,它是在 .NET 3.5 中引入的。它使 .NET 语言能够生成查询以从数据源中检索数据。它消除了编程语言和数据库之间的不匹配,并且无论使用哪种类型的数据源,用于创建查询的语法都是相同的。在本文中,我们将以员工数据中的员工姓名包含少于四个字符的员工数据为例,演示如何使用该方法作为条件。所以对于这个任务,我们使用 Where()函数。此函数根据给定条件过滤给定数组。或者我们可以说 Where() 方法根据指定的条件从序列中返回值。
例子:
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 function named “checkstring” which check the length of the string is less than 4 characters.i.e., str.Length < 4.
- 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 => checkstring(employee))”.
- Display the employee names.
例子:
C#
// C# program to illustrate the use of
// the method as a condition in the
// LINQ where() method of the list collection
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
// Function to check the given string is less than 4
static bool checkstring(string str)
{
if (str.Length < 4)
return true;
else
return false;
}
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 => checkstring(employee));
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