Lamda表达式的一个有意思的例子

本文介绍如何在C#中利用Lambda表达式对员工薪酬进行预测,通过实例展示了如何定义和应用Lambda表达式来筛选员工薪酬超过特定数值的员工。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LamdaDemo
{
    class Employee
    {
        public string EmployeeID;
        public decimal Salary;
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> listeEmployees = new List<Employee>()
            {
                new Employee(){ EmployeeID = "YT004", Salary = 1000},
                new Employee(){ EmployeeID = "YT005", Salary = 2000},
                new Employee(){ EmployeeID = "YT006", Salary = 3000}
            };

            Func<Employee, decimal, bool> predict = (e, d) => (e.Salary > d);

            bool result = predict(listeEmployees[1], 1500);

            Console.WriteLine(result);

            Console.ReadKey();
        }
    }
}

结果


### 使用 Lambda 表达式对集合进行过滤并计算符合条件的元素个数 在 Java 中,可以使用 Stream API 和 Lambda 表达式来对集合中的元素进行过滤,并计算符合条件的元素个数。以下是一个完整的解决方案[^1]。 ```java import java.util.*; import java.math.BigDecimal; import java.util.stream.Collectors; class Apple { private int id; private String name; private BigDecimal price; private int quantity; public Apple(int id, String name, BigDecimal price, int quantity) { this.id = id; this.name = name; this.price = price; this.quantity = quantity; } public int getId() { return id; } public String getName() { return name; } public BigDecimal getPrice() { return price; } public int getQuantity() { return quantity; } } public class Main { public static void main(String[] args) { List<Apple> appleList = new ArrayList<>(); appleList.add(new Apple(1, "苹果1", new BigDecimal("3.25"), 10)); appleList.add(new Apple(1, "苹果2", new BigDecimal("1.35"), 20)); appleList.add(new Apple(2, "香蕉", new BigDecimal("2.89"), 30)); appleList.add(new Apple(3, "荔枝", new BigDecimal("9.99"), 40)); // 使用 Lambda 表达式过滤并计算符合条件的元素个数 long count = appleList.stream() .filter(apple -> apple.getPrice().compareTo(new BigDecimal("3.00")) > 0) // 过滤价格大于 3.00 的苹果 .count(); System.out.println("符合条件的苹果数量: " + count); } } ``` 上述代码中,`appleList.stream()` 创建了一个流对象,允许我们对集合中的元素执行一系列操作。`.filter()` 方法用于根据条件过滤元素,而 `.count()` 方法则用于统计满足条件的元素个数[^2]。 ### 注意事项 - 在 `filter` 方法中,Lambda 表达式的逻辑可以根据具体需求进行调整。例如,这里过滤的是价格大于 3.00 的苹果。 - 如果需要对其他属性进行过滤,只需修改 `filter` 方法中的条件即可[^3]。 ### 示例输出 假设测试数据如下: ```java Apple apple1 = new Apple(1, "苹果1", new BigDecimal("3.25"), 10); Apple apple12 = new Apple(1, "苹果2", new BigDecimal("1.35"), 20); Apple apple2 = new Apple(2, "香蕉", new BigDecimal("2.89"), 30); Apple apple3 = new Apple(3, "荔枝", new BigDecimal("9.99"), 40); ``` 运行结果为: ``` 符合条件的苹果数量: 2 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值