-2

I have two values in the dictionary but when I try to get the two values outside the loop I am only getting one value. The locationdesc variable value are being overwritten. Is there a better way to create unique variables to handle this issues

There are two keys location-1 and location-2. I am trying to figure out how to get both the values outside the loop. Am I doing it wrong?

string locationDesc = "";
string locationAddress = "";

int count = dictionary.Count(D => D.Key.StartsWith("location-"));

for (int i = 1; i <= count; i++)
{
    if (dictionary.ContainsKey("location-"+i))
    {
        string locationData = dictionary["location-"+i];
        string[] locationDataRow = locationData.Split(':');
        locationDesc = locationDataRow[0];
        locationAddress = locationDataRow[1];
    }
}
// Only getting location-2 value outside this loop since locationDesc is not unique.
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress);

What I would like to get here is get both the values like locationDesc1 and locationDesc2 instead of locationDesc

What I am looking for is to create locationDesc and locationAddress unique so I can access both the values outside the for loop.

More Explanation as I was not very clear:

I have a dynamic table that will be created in the front end. Every time a location is created I create a cookie. For e.g. location-1, location-2 ...location-n with the location description and location values as values in the cookie. I am trying to access these values in the backend by creating a dictionary so I can assign all the values to unique variable which will make it easier for me to pass these values to a api call. I think I am over complicating a simple issue and might be doing it wrong.

My api call will be something like this:

<field="" path="" value=locationDesc1>
<field="" path="" value=locationDesc2>
NepCoder
  • 429
  • 4
  • 16
  • What exactly are you trying to do? – kjaquier Aug 24 '16 at 16:06
  • trying to get both the key values outside the loop so access the values outside the loop. – NepCoder Aug 24 '16 at 16:07
  • you already can, that's what the loop is, you just need to specify which key to use. All of your values are already saved in `dictionary` – Dispersia Aug 24 '16 at 16:08
  • It's really not clear what this code is trying to do. Are you trying to find the first element where the key matches `location-x`? – DavidG Aug 24 '16 at 16:09
  • Just trying to get both the key values outside the for loop.Right now I am only getting the second one since its being overridden. – NepCoder Aug 24 '16 at 16:10
  • 2
    Why not just do `var values = dictionary.Where(d => d.Key.StartsWith("location-"));`? Then no loop is needed. – DavidG Aug 24 '16 at 16:11
  • Like this? [http://stackoverflow.com/questions/141088/what-is-the-best-way-to-iterate-over-a-dictionary-in-c](http://stackoverflow.com/questions/141088/what-is-the-best-way-to-iterate-over-a-dictionary-in-c) ? – kjaquier Aug 24 '16 at 16:11
  • Just replace you assignment with a direct 'WriteLine' in the loop. You are overwriting values due to a context existing outside a loop. So it will always be the last value. If you just want to prove your loop is working just add a writeline instead of the assignments. Otherwise you are just making it more complex than necessary – djangojazz Aug 24 '16 at 16:18
  • My loop is working. If I put the writeline inside I am getting both the values. What I am trying to do is get both the values outside the forloop so I can pass it to a api call. – NepCoder Aug 24 '16 at 16:19
  • What do you mean by 'get both values'? Without knowing the type of 'locationDesc' and 'locationAddress' one would most likely assume they are either string or object types. What is your end goal? When you say pass to an API you can do that inside the loop as well like 'DoSomething(locationDataRow[0])' – djangojazz Aug 24 '16 at 16:22
  • 1
    @kjaquier What on earth does this question have to do with Javascript? – DavidG Aug 24 '16 at 16:23
  • @DavidG Ooooh sorry my mistake. Wrong topic... – kjaquier Aug 24 '16 at 16:48

4 Answers4

2

The problem with your loop is that you are relying on the position of the entry in the dictionary matching the index within your loop. Your first line of code pretty much has it though:

int count = dictionary.Count(D => D.Key.StartsWith("location-"));

What this tells me is that you are looking for all entries in your dictionary where the key starts with "location-". So why not do that directly:

var values = dictionary.Where(d => d.Key.StartsWith("location-"));

And to do the extraction/string splitting at the same time:

var values = dictionary
    .Where(d => d.Key.StartsWith("location-"))
    .Select(d => d.Item.Split(':')
    .Select(s => new 
    { 
        LocationDesc = s[0], 
        LocationAddress = s[1]
    });

This will give you an IEnumerable of LocationDesc/LocationAddress pairs which you can loop over:

foreach(var pair in values)
{
    Debug.WriteLine(pair.LocationDesc);
    Debug.WriteLine(pair.LocationAddress);
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

Try this:

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
Dictionary<string, string> values = new Dictionary<string, string>();
for (int i = 1; i <= count; i++)
{
    if (dictionary.ContainsKey("location-"+i))
    {
        string locationData = dictionary["location-"+i];
        string[] locationDataRow = locationData.Split(':');
        values.Add(locationDataRow[0],locationDataRow[1]);
    }
}
foreach (var item in values)
{
    Debug.WriteLine(item.Key + " : " + item.Value);
}
Umair M
  • 10,298
  • 6
  • 42
  • 74
0

As you are dealing with multiple values, you should go with a container where you can store all the values.

if you are dealing with only two unique values then use below code.

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
string[] locationDesc = new string[2];
string[] locationAddress = new string[2];
    for (int i = 1; i <= count; i++)
    {
        if (dictionary.ContainsKey("location-"+i))
        {
            string locationData = dictionary["location-"+i];
            string[] locationDataRow = locationData.Split(':');
            locationDesc[i-1] = locationDataRow[0];
            locationAddress[i-1] = locationDataRow[1];
        }
    }

for (int i = 0; i <= locationDesc.Length-1; i++)
{
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}    

if number of unique values is not fixed then go with ArrayList

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
ArrayList locationDesc = new ArrayList();
ArrayList locationAddress = new ArrayList();
    for (int i = 1; i <= count; i++)
    {
        if (dictionary.ContainsKey("location-"+i))
        {
            string locationData = dictionary["location-"+i];
            string[] locationDataRow = locationData.Split(':');
            locationDesc.Add(locationDataRow[0]);
            locationAddress.Add(locationDataRow[1]);
        }
    }

for (int i = 0; i < locationDesc.Count; i++)
{
    Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
    Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}

Simple One. If you only want to show result using Debug.WriteLine, then go with below code

int count = dictionary.Count(D => D.Key.StartsWith("location-"));

    for (int i = 1; i <= count; i++)
    {
        if (dictionary.ContainsKey("location-"+i))
        {
            string locationData = dictionary["location-"+i];
            string[] locationDataRow = locationData.Split(':');
            Debug.WriteLine("Location Desc from dictionary is : " + locationDataRow[0]);
            Debug.WriteLine("Location Add from dictionary is : " + locationDataRow[1]);
        }
    }

Not able to prepare Code in Visual Studio at the moment therefore there may be some syntax errors.

maulik kansara
  • 1,087
  • 6
  • 21
0

It is hard to judge what you are event trying to do. I would not just be dumping objects you already have into other objects for fun. If you are just trying to expose values in a loop for use with another function, you can just use LINQ to iterate over the dictionary. If you want a specific value just add a where LINQ expression. LINQ should be in any .NET framework after 3.5 I believe.

public static void ApiMock(string s)
{
  Console.WriteLine($"I worked on {s}!");
}

static void Main(string[] args)
{
  var d =  new Dictionary<int, string> {
      {  1, "location-1" },
      {  2, "location-2" },
      {  3, "location-3" }
  };

  d.ToList().ForEach(x => ApiMock(x.Value));

  //I just want the second one
  d.Where(x => x.Value.Contains("-2")).ToList().ForEach(x => ApiMock(x.Value));

  //Do you want a concatenated string
  var holder = string.Empty;
  d.ToList().ForEach(x => holder += x.Value + ", ");
  holder = holder.Substring(0, holder.Length - 2);

  Console.WriteLine(holder);
}
djangojazz
  • 14,131
  • 10
  • 56
  • 94