在SortedList中按特定条件查找/删除项目,可以通过以下步骤实现:
以下是一个示例代码,演示如何在SortedList中按特定条件查找/删除项目:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
SortedList<int, string> sortedList = new SortedList<int, string>();
// 添加项目到SortedList
sortedList.Add(1, "Apple");
sortedList.Add(2, "Banana");
sortedList.Add(3, "Orange");
sortedList.Add(4, "Grapes");
// 按特定条件查找项目
int keyToFind = 2;
if (sortedList.ContainsKey(keyToFind))
{
string value = sortedList[keyToFind];
Console.WriteLine($"Found item with key {keyToFind}: {value}");
}
else
{
Console.WriteLine($"Item with key {keyToFind} not found");
}
string valueToFind = "Orange";
if (sortedList.ContainsValue(valueToFind))
{
int key = sortedList.FirstOrDefault(x => x.Value == valueToFind).Key;
Console.WriteLine($"Found item with value {valueToFind}: {key}");
}
else
{
Console.WriteLine($"Item with value {valueToFind} not found");
}
// 按特定条件删除项目
int keyToDelete = 3;
if (sortedList.ContainsKey(keyToDelete))
{
sortedList.Remove(keyToDelete);
Console.WriteLine($"Item with key {keyToDelete} deleted");
}
else
{
Console.WriteLine($"Item with key {keyToDelete} not found");
}
string valueToDelete = "Grapes";
if (sortedList.ContainsValue(valueToDelete))
{
int key = sortedList.FirstOrDefault(x => x.Value == valueToDelete).Key;
sortedList.Remove(key);
Console.WriteLine($"Item with value {valueToDelete} deleted");
}
else
{
Console.WriteLine($"Item with value {valueToDelete} not found");
}
}
}
这个示例代码演示了如何使用SortedList在特定条件下查找和删除项目。请注意,这只是一个示例,实际应用中可能需要根据具体需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云