C# Find()和First()与FirstOrDefault()

本文详细对比了Find和FirstOrDefault在List<T>和IEnumerable<T>上的应用,解释了Find基于Array查找,而FirstOrDefault采用foreach查找,前者速度更快。阐述了First与FirstOrDefault在元素存在性检查上的区别,以及在实际编程中如何根据情况选择使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Find方法只能在List<T>上使用,而后者能更广泛应用在IEnemerable<T>上。

Find最终是建立在Array的查找之上,而在IEnemerable上的FirstOrDefault是使用foreach查找的。因此,Find速度会比FirstOrDefault快很多,据测试可能会快一倍以上。

2. First:取序列中满足条件的第一个元素,如果没有元素满足条件,则抛出异常 
3. FirstOrDefault:取序列中满足条件的第一个元素,如果没有元素满足条件,则返回默认值(对于可以为null的对象,默认值为null,对于不能为null的对象,如int,默认值为0) 
First、FirstOrDefault的区别在于:当没有元素满足条件时,一个抛出异常,一个返回默认值。 
因此,在使用时,一定要注意这个区别: 
1、当确信序列中一定有满足条件的元素时,使用First方法,取到元素后,无需判断是否为null 
2、当序列中可能找不到满足条件的元素时,使用FirstOrDefault方法,然后,一定要对返回值是否为null,进行不同的处理

这里是一个完整的 C# WebSocket 创建聊天室的示例代码,包括创建 WebSocket 服务器对象、实现 Echo 类、实现 ChatRoomManager 类等。 ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebSocketSharp; using WebSocketSharp.Server; namespace WebSocketChatRoom { class ChatRoom { private string _roomId; private List<WebSocket> _clients; public ChatRoom(string roomId) { _roomId = roomId; _clients = new List<WebSocket>(); } public void AddClient(WebSocket client) { _clients.Add(client); } public void RemoveClient(WebSocket client) { _clients.Remove(client); } public void Broadcast(string message) { foreach (var client in _clients) { client.Send(message); } } } class ChatRoomManager { private static List<ChatRoom> _activeRooms = new List<ChatRoom>(); public static void CreateNewRoom() { // Generate a unique ID for the new chat room string roomId = Guid.NewGuid().ToString(); // Create a new chat room object var room = new ChatRoom(roomId); // Add the chat room to the list of active chat rooms _activeRooms.Add(room); } public static string GetAvailableRoomId() { // Find the first available chat room ID for (int i = 0; i < 100; i++) { string roomId = i.ToString("D2"); if (!_activeRooms.Any(r => r.RoomId == roomId)) { return roomId; } } throw new ApplicationException("No available chat room ID found."); } public static void JoinRoom(string roomId, WebSocket client) { // Find the chat room with the specified ID var room = _activeRooms.FirstOrDefault(r => r.RoomId == roomId); if (room == null) { throw new ApplicationException($"Chat room with ID {roomId} not found."); } // Add the client to the chat room room.AddClient(client); // Send a welcome message to the client client.Send($"Welcome to chat room {roomId}!"); } public static void LeaveRoom(string roomId, WebSocket client) { // Find the chat room with the specified ID var room = _activeRooms.FirstOrDefault(r => r.RoomId == roomId); if (room == null) { throw new ApplicationException($"Chat room with ID {roomId} not found."); } // Remove the client from the chat room room.RemoveClient(client); } public static void Broadcast(string roomId, string message) { // Find the chat room with the specified ID var room = _activeRooms.FirstOrDefault(r => r.RoomId == roomId); if (room == null) { throw new ApplicationException($"Chat room with ID {roomId} not found."); } // Broadcast the message to all clients in the chat room room.Broadcast(message); } } class ChatRoomBehavior : WebSocketBehavior { private string _roomId; protected override void OnOpen() { // Get the ID of the new chat room string roomId = ChatRoomManager.GetAvailableRoomId(); // Join the chat room ChatRoomManager.JoinRoom(roomId, this); // Save the chat room ID to the behavior object _roomId = roomId; } protected override void OnMessage(MessageEventArgs e) { // Broadcast the message to all clients in the chat room ChatRoomManager.Broadcast(_roomId, e.Data); } protected override void OnClose(CloseEventArgs e) { // Leave the chat room ChatRoomManager.LeaveRoom(_roomId, this); } } class Program { static void Main(string[] args) { // Create a WebSocket server on port 8080 var wssv = new WebSocketServer(8080); // Add the ChatRoom behavior to the server wssv.AddWebSocketService<ChatRoomBehavior>("/ChatRoom"); // Start the server wssv.Start(); // Create a new chat room ChatRoomManager.CreateNewRoom(); // Wait for input to stop the server Console.WriteLine("Press any key to stop the server..."); Console.ReadLine(); // Stop the server wssv.Stop(); } } } ``` 在这个示例代码中,我们创建了一个 ChatRoom 类,用于表示聊天室对象;创建了一个 ChatRoomManager 类,用于管理聊天室;创建了一个 ChatRoomBehavior 类,用于处理客户端的 WebSocket 请求。在 Main 方法中,我们创建了一个 WebSocket 服务器对象,并将 ChatRoomBehavior 添加到服务器中。然后,我们创建了一个新的聊天室,并等待用户输入以停止服务器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值