c# 从一个词典的值中查找另一个词典的键 获取键列表
时间: 2024-03-07 20:48:49 浏览: 22
如果您想要查找一个字典的值是否包含在另一个字典的键中,并获得匹配的键列表,可以使用LINQ语句来实现。以下是一个示例代码:
```csharp
Dictionary<int, string> dict1 = new Dictionary<int, string>()
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, "Five" }
};
Dictionary<string, int> dict2 = new Dictionary<string, int>()
{
{ "Two", 2 },
{ "Three", 3 }
};
var result = dict1.Where(kv => dict2.ContainsValue(kv.Value))
.Select(kv => kv.Key)
.ToList();
foreach (int key in result)
{
Console.WriteLine(key);
}
```
在上面的示例中,我们首先定义了两个字典`dict1`和`dict2`。然后我们使用LINQ语句来查找`dict1`字典中的值是否包含在`dict2`字典的键中。我们使用`Select`方法来选择匹配元素的`Key`属性,并将结果存储在一个`List<int>`对象中。最后,我们循环遍历结果列表并打印每个键。
相关问题
c# 获取词典最后一个键
在C#中,可以使用 Dictionary<TKey, TValue> 类来表示一个键值对的集合。如果你想要获取字典中最后一个键,可以使用 Keys 属性获取所有的键,然后通过索引获取最后一个键。下面是一个简单的例子:
```
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("orange", 3);
string lastKey = dict.Keys.Last();
Console.WriteLine("The last key in the dictionary is: " + lastKey);
```
在这个例子中,我们创建了一个字典,然后使用 Keys 属性获取所有的键。接着,我们使用 Linq 的 Last 方法获取最后一个键,并将结果赋值给变量 lastKey。最后,我们输出最后一个键的值。注意,如果字典为空,则调用 Last 方法会抛出异常。
c# 在列表中查找另一个列表的值 获得id列表
如果您想要查找一个列表中包含另一个列表的值,并获得匹配的元素的ID列表,可以使用LINQ语句来实现。以下是一个示例代码:
```csharp
class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
List<Item> itemList = new List<Item>()
{
new Item { Id = 1, Name = "Item 1" },
new Item { Id = 2, Name = "Item 2" },
new Item { Id = 3, Name = "Item 3" },
new Item { Id = 4, Name = "Item 4" },
new Item { Id = 5, Name = "Item 5" }
};
List<int> searchList = new List<int>() { 2, 3 };
var result = itemList.Where(item => searchList.Contains(item.Id))
.Select(item => item.Id)
.ToList();
foreach (int id in result)
{
Console.WriteLine(id);
}
```
在上面的示例中,我们首先定义了一个`Item`类,其中包含`Id`和`Name`属性。然后我们创建了一个包含几个`Item`对象的`itemList`列表和一个要查找的ID列表`searchList`。接下来,我们使用LINQ语句来查找`itemList`列表中的元素,其中ID值包含在`searchList`列表中。我们使用`Select`方法来选择匹配元素的`Id`属性,并将结果存储在一个`List<int>`对象中。最后,我们循环遍历结果列表并打印每个ID。