【解決方法】linq where および select C# を使用して辞書値を取得するにはどうすればよいですか?

プログラミングQA


やあ

価値を得ようとしている

"1790,1234,345,67"

変数に

getProductValue 

。 しかし、それは私からは届いていません

dictionary

物体。

私が試したこと:

C#
Dictionary<int, string> dictionary = new Dictionary<int, string>();
IEnumerable<string> getProductValue = new string[] { };
dictionary.Add(1, "0,1,2");
dictionary.Add(3, "1790,1234,345,67");
if (dictionary.ContainsKey(3))
{
    getProductValue = dictionary.Where(d => d.Key == 3).Select(d => d.Value).ToString().Split(new string[] { "," }, StringSplitOptions.None); 
}

期待される出力:

getProductValue = "1790,1234,345,67" 

カンマ区切りの値。

ありがとう

解決策 1

Google 検索は、この種の質問を調べるのに強力です。 あなたの代わりにGoogle検索に入れておきます: linq where および select C# を使用して辞書値を取得するにはどうすればよいですか? – Google検索[^]

最初の検索結果は次のとおりでした。 Linq クエリ ディクショナリのリストの値 [solved] – スタックオーバーフロー[^]。 その検索にはさらに多くの答えがあります。

したがって、それに基づいて、次のようにします。

C#
var results = dictionary
    .Where(x => x.Key == 3)
    .Select(x=> x.Value)
    .FirstOrDefault();

getProductValue = results.Split(',');

コメント

タイトルとURLをコピーしました