![](/img/trans.png)
[英]Copy a dictionary with int List <int, List<int>> by value
[英]Find value in Dictionary<int,List<int>>
我有一本帶有int鍵和List值的字典
我想找出鍵或值是否包含特定的整數並獲取相關的鍵。
例:
Dictionary<int, List<int>> removableStuff = new Dictionary<int, List<int>>();
removableStuff.Add(1, new List<int> {1});
removableStuff.Add(3, new List<int> {9,33,35});
removableStuff.Add(2, new List<int> {1,65,32,3});
我想找到數字3。由於可以找到3作為鍵和值,因此輸出為:3、2。
這應該產生期望的結果:
var num = 3;
var keys = removableStuff.Where(i => i.Key.Equals(num) || i.Value.Any(num.Equals))
.Select(i => i.Key);
如果不想處理Enumerable,則可以選擇在.Select()
.ToList()
之后調用.ToList()
。
i.Value.Any(num.Equals)
也可以簡化為i.Value.Contains(num)
,但是當我使用Linq時,我也喜歡將Any
用作此類東西。 (只是個人喜好)
盡管如此,這是非常基本的Linq,我相信您會在詢問之前找到答案。
與Tobias的答案類似的方法是使用Contains
而不是Any(Equals)
:
Dictionary<int, List<int>> removableStuff = new Dictionary<int, List<int>>
{
{1, new List<int> {1}},
{3, new List<int> {9, 33, 35}},
{2, new List<int> {1, 65, 32, 3}}
};
int find = 3;
var matches = removableStuff.Where(item => item.Key == find || item.Value.Contains(find));
foreach (var match in matches)
{
Console.WriteLine($"{match.Key}: {string.Join(", ", match.Value)}");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.