日期:
来源:Linux公社收集编辑:聆听世界的鱼
点击上方蓝字 ● 关注Linux公社
using System;using System.Collections.Generic;using Systems.Linq;public class LinqMethodExample{public static void Main(string[] args){// 创建一个整数列表。var listOfNumbers = new List<int> { 10, 5, 20, 15, 30, 25, 33, 66 };// 执行各种LINQ方法。var result = listOfNumbers.Where(num => num % 5== 0) // 得到可被5整除的数字。.Select(num => (int)Math.Pow(num, 2)) // 将每个数字平方。.Skip(1) // 跳过第一个元素。.Last(num => num % 2 == 0) // 得到最后一个偶数。Console.WriteLine($"{result}");// 样例输出:// 900}}
OrderBy() -> 根据谓词按升序对序列进行排序。 GroupBy() -> 根据谓词对元素进行分组。 SelectMany() -> 扁平化嵌套列表(即从 List<List<int>> 提取 List<int>)。 Join() -> 根据谓词连接两个序列。 Zip() -> 将两个序列组合成元组的单个序列。 Distinct() -> 从序列中返回不同的元素。
using System;using System.Threading.Tasks;public class AsyncProgramming{public static async Task RandomDelayAsync(int workId){// 为此给定任务设置一个随机延迟值(1s-5s)。var rand = new Random();var delay = rand.Next(1000, 5000);await Task.Delay(delay);// 打印消息,以便用户知道此任务何时完成。Console.WriteLine($"Work {workId} completed in {delay}ms.");}public static async Task Main(){// 创建一个由3个任务组成的数组以异步执行。var tasks = new Task[3];for (var idx=0; idx < tasks.Length; idx++){tasks[idx] = RandomDelayAsync(idx);}// 等待所有任务完成。await Task.WhenAll(tasks);Console.WriteLine("All tasks completed.");// 示例输出:// Work 2 completed in 1014ms.// Work 0 completed in 2329ms.// Work 1 completed in 4392ms.// All tasks completed.}}
using System;public class DelegateAndEventExample{// 声明表示方法的委托类型// 不接受任何参数并返回void。public delegate void PhoneNumber();public class Class{// 声明类型为PhoneNumber的事件。public event PhoneNumber VoiceMail;// 定义引发事件的方法。public void CallPhoneNumber(){Console.WriteLine("Calling the phone number...");MyEvent?.Invoke();}}public static void Main(){var instance = new MyClass();// 使用lambda表达式将方法附加到语音邮件事件。instance.VoiceMail += () => Console.WriteLine("Event handler called!");// 调用CallPhoneNumber方法,该方法会引发语音邮件事件。instance.CallPhoneNumber();// 示例输出:// Calling the phone number...// Event handler called!}}
链接:https://www.linuxmi.com/c-sharp-prodigy.html
关注我们 长按或扫描下面二维码关注 Linux公社
关注 Linux公社,添加“ 星标 ”
每天 获取 技术干货,让我们一起成长
合作联系:root@linuxidc.net