どうも、ちょげ(@chogetarou)です。
Where()を使ってDictionary(辞書)に指定した条件を満たす値(value)からキー(Key)を取得する方法を紹介します。
方法

Where()を使ってDictionary(辞書)に指定した条件を満たす値(value)からキー(Key)を取得するには、Select()を使います。
まず、System.Linqを導入します。
using System.Linq;
次に、Dictionary(辞書)からWhere()を呼び出します。
Where()の引数に、値(Value)の条件式を返すラムダ式を指定します。
値(value)の条件式では、Dictionaryの値を引数のValueプロパティで表現します。
そして、Where()からSelect()を呼び出します。
Select()の引数に、引数のKeyプロパティを返すラムダ式を指定します。
//item.Valueで値を取得
var result = dict.Where(item => 値の条件式)
.Select(item => item.Key);
上記のSelect()は、Where()のラムダ式でTrueを返した値からキーを取得します。
使用例
using System;
using System.Linq;
using System.Collections.Generic;
public class Sample
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
};
//奇数の値からキーを取得
var result = numbers.Where(item => item.Value % 2 == 1)
.Select(item => item.Key);
foreach(var item in result)
{
Console.WriteLine(item);
}
}
}
出力:
one
three
five
コメント