我有一个数组列表,其中包含名为 Room 的项目。每个房间都有一个房间类型,例如厨房、接待处等。 在将它添加到列表之前,我想检查 arraylist 以查看是否存在该类型的房间。 谁能推荐一种不需要多个 foreach 循环的巧妙方法?
(.NET 2.0)
我无法访问在 .net 2.0 上运行的 linq 技术。我应该在问题中说明这一点。 抱歉
最佳答案
我不会使用 ArrayList
这里;因为你有 .NET 2.0,所以使用 List<T>
一切都变得简单了:
List<Room> rooms = ...
string roomType = "lounge";
bool exists = rooms.Exists(delegate(Room room) { return room.Type == roomType; });
或使用 C# 3.0(仍以 .NET 2.0 为目标)
bool exists = rooms.Exists(room => room.Type == roomType);
或者使用 C# 3.0 和 LINQBridge或 .NET 3.5:
bool exists = rooms.Any(room => room.Type == roomType);
(Any
用法适用于更多类型,而不仅仅是 List<T>
)
关于c# - 检查 arraylist 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289794/