Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am trying to get value
"1790,1234,345,67"
to the variable
getProductValue 
. But it is not getting from my
dictionary
object.

What I have tried:

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); 
}


Expecting output:
getProductValue = "1790,1234,345,67" 
comma separated values.

Thanks
Posted
Updated 6-Jul-23 22:36pm

Google search is powerful for looking up this type of question. I put it into google search for you: How do I get dictionary value by using linq where and select C#? - Google Search[^]

The first search result was: Linq Query Dictionary where value in List [solved] - StackOverflow[^]. There are plenty more answers in that search.

So, based on that, you would do:
C#
var results = dictionary
    .Where(x => x.Key == 3)
    .Select(x=> x.Value)
    .FirstOrDefault();

getProductValue = results.Split(',');
 
Share this answer
 
v3
That's a really terrible way to get the value associated with the specified key!

Instead, use the TryGetValue method[^]:
C#
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
    [1] = "0,1,2",
    [3] = "1790,1234,345,67"
};

IEnumerable<string> getProductValue = dictionary.TryGetValue(3, out string value)
    ? value.Split(new char[] { ',' }, StringSplitOptions.None)
    : Array.Empty<string>();

Better yet, if you're always returning a list of strings, change your dictionary type so that you don't need to split the string:
C#
Dictionary<int, string[]> dictionary = new Dictionary<int, string[]>
{
    [1] = ["0", "1", "2"],
    [3] = ["1790", "1234", "345", "67"]
};

if (!dictionary.TryGetValue(3, out string[] getProductValue))
{
    getProductValue = Array.Empty<string>();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900