deconstruct array into variables?

pythonatSheriff

Full Stack Web Developer
Joined
Dec 15, 2021
Messages
25
Location
Egypt
Programming Experience
1-3
I have an array of unlimited number of strings and I need to deconstruct this array into variables, so I searched for built-in method but in vain, so I decided to make my own function :
C#:
 public static void Deconstruct(this string[] strArr, out params string)
                {
                 for (int i = 0; i < strArr.Length; i++)
                     {
                         s[i] = strArr[i];
                     }

                }
There is something wrong in using "params" as out , how can I make such a function, please ?
 
Last edited by a moderator:
You can't make such a function. It makes no sense. Even if you could use params for output, a parameter declared params is an array anyway. The only thing you could do would be to define an iterator, which would return the elements one by one as an IEnumerable<string>, but an array is already an IEnumerable<T>, so you gain nothing. If you actually want individual variables then you have to know how many elements there will be ahead of time, because every variable has to be declared.

Please explain what you're actually trying to achieve, rather than how you're trying to achieve it, and we will try to explain what you actually need to do.
 
Thanks for declaring many things to me. So, my real challenge is :
Have the function SearchingChallenge(strArr) read in the strArr parameter containing key:value pairs where the key is a string and the value is an integer. Your program should return a string with new key:value pairs separated by a comma such that each key appears only once with the total values summed up.
For example: if strArr is ["B:-1", "A:1", "B:3", "A:5"] then your program should return the string A:6,B:2.
__________________________________________________________________

now, let me tell you my approach to solve this problem (maybe it is bad)
1- I need to store that string in a variable i.e. var x = "x:-1"
2- then I need to split that string into two strings by using Split(":");
3- now I have two strings i.e. string[] twoStrings = ["x", "-1"];
4- convert "-1" to integer to be able to add to another variable

_________________________________________________________

My second thought after your message and a lot of googling :
C#:
    string[] strArr = new string[] {"X:-1", "Y:1", "X:-4", "B:3", "X:5"};
    Dictionary<string, string> Mapping = new Dictionary<string, string>();
    Mapping = strArr.ToDictionary(key => key, value => value);
        foreach(var item in Mapping)
    {
        Console.WriteLine(item.Key);
        Console.WriteLine(item.Value);
    }
_______ // this is the output :
X:-1
X:-1
Y:1
Y:1
X:-4
X:-4
B:3
B:3
X:5
X:5

____ Now, as I have keys equal to values (( key:value = "X:-1" : "X-1" ))
I am thinking about Dictionary.Remove(value) and then try to manipulate or divided the "key" to "x" and "-1", but I am still searching for a way to do so
as I don't know if is it possible or not.
which approach should I follow? and if there is another way to solve it, I would be appreciated if you enlightened me.
Thanks in advance.
 
Please put your code in code tags. It'll help keep your code's formatting/indentation and make it easier for everyone to read.
 
You were close with your first though.

Try this pseudo-code:
C#:
var dictionary = new Dictionary<string, int>();
foreach(var entry in strArray)
{
    var parts = entry.Split(':');
    var key = parts[0];
    var value = int.Parse(parts[1]);

    if(dictionary.ContainsKey(key))
        dictionary[key] = dictionary[key] + value;
    else
        dictionary[key] = value;
}

I'll let you noodle a bit on how to return that single string. I suggest using a StringBuilder to make formatting easier, but you could get by with just plain concatenation.
 
c-sharp searching and combine function:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

class MainClass
{

  public static void Main(string[] arg1)
   {

    string[] strArr = new string[] {"X:-1", "Y:1", "X:-4", "B:3", "X:5"};

    Dictionary<string, string> Mapping = new Dictionary<string, string>();

    foreach(var entry in strArr)
    {
      var Parts = entry.Split(":");
      var Key = Parts[0];
      var Value = Parts[1];

      if(Mapping.ContainsKey(Key))
        Mapping[Key] = Mapping[Key] + Value ;
      else
        Mapping[Key] = Value;

      char[] LooseInteger;
      LooseIneger = Mapping[Key].ToCharArray();
      if(LooseIneger.Length > 1)
      {
          for (int i = 0; i < LooseIneger.Length; i++)
          {
          Console.WriteLine(LooseIneger[i]);
          }
      }
      else if (LooseIneger <= 1)
      {
          Console.WriteLine(LooseIneger[i]);
      }

        string sign_n_number;
        StringBuilder ValueDeconstruct = new StringBuilder();
        for (int i = 0; i < 2; i++)
        {
            sign_n_number.Append(LooseIneger[i]);
        }
        string one_number = Int32.Parse(sign_n_number.ToString());
        
      
    }


        foreach(var item in Mapping)
    {
        //Console.WriteLine(item.Key);
        Console.WriteLine(item.Value);
    }



        

   }

}


Now, I have more than one issue in my code. Firstly, the output error : the name "LooseInteger" deos not exist in the current context. Secondly, when I built my StringBuilder I assumed that it will combine 2 characters, but before adding lines starts from line 27, the output was like this :
-1-45
1
3
>> this means that Values with positive sign will not be separated correctly because in the previous output there is no positive sign (-1-4+5),
so If the Values comes out like this (-1-45678), they will be -1,-4,56,78 as the StringBuilder output.
>> I thought a lot about the hint of (concatenation), but it leads me to the same logic, so, I guess first I need to work around with positive sign in the very
beginning, and if there is a positive number I shall insert (+) before it to ensure it will StringBuilder correctly and hence the calculations will be correct.
Please I need help, :) ?
 
By the way, I really appreciated your quick response for all my inquiries. You guys are terrific and I really mean it without any flattery.
 
Look closer at the error you are getting. It's likely "LooseIneger" without the 't' in it. Then look at line 28 of post #8. Notice that it's also missing a 't', but the variable you declared on line 27 has a 't'.

Anyway the main thing is that you want to do all the strArray processing in one loop. That will update the dictionary with the final values. Then when the first loop as completed, iterate over the dictionary and build up your string. As a hint, you don't need to convert anything into character arrays. Simply use StringBuilder.AppendFormat(). That will be like using Console.Write("{0} : {1}", key, value);.
 
Last edited:
For example: if strArr is ["B:-1", "A:1", "B:3", "A:5"] then your program should return the string A:6,B:2.

Based on the above, you don't need to build a string with the pluses and minuses. You just need a string with the results of the sum of the values.
 
Looks like the keys in output should be sorted too :)
 
searching function in c-sharp:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

class MainClass
{

  public static void Main(string[] arg1)
  {

    string[] strArr = new string[] {"X:-1", "Y:1", "X:-4", "B:3", "X:5"};

    Dictionary<string, string> Mapping = new Dictionary<string, string>();
    int value_int = 0;
    foreach(var entry in strArr)
    {
      var Parts = entry.Split(":");
      var Key = Parts[0];
      var Value = Parts[1];

      if(Mapping.ContainsKey(Key))
        Mapping[Key] = Mapping[Key] + Value ;
      else
        value_int = Int32.Parse(Value);
        //value_int += value_int;
        Mapping[Key] = value_int.ToString();
    }


        foreach(var item in Mapping)
    {
        //Console.WriteLine(item.Key);
        Console.WriteLine(item.Value);
    }


:cry: I didn't get sleep for 2 days, and my age is 42, so please forgive me for missing out the "t" in "LooseInteger".
Ok, NOW I understand that I need to set my dictionary right first and then iterate over it to StringBuilder.AppendFormat like this one :
snippet from another website:
class Program
{
    static void Main()
    {
        StringBuilder builder = new StringBuilder();
        string value = "ABC";
        int number = 1;
        // Combine the 2 values with AppendFormat.
        builder.AppendFormat("R: {0} ({1}).", value, number);
        Console.WriteLine(builder);
    }
}
NOW, I have tried to get the sum of (-1-45) as the output for (X), but all of my trials came in vain. Is there a function that combine -ve and +ve numbers after converting it from string to int?

Thanks for your patience ... 😍
😘
 
I forgot to mention that my latest code result was :
3
1
3
// and I don't know how the first (3) came to being, although I'm a structure engineer but never came with a result, maybe my brain burned out :)
 
Why did you change value type to string in dictionary? The code @Skydiver posted was working fine to sum the values.
 
Back
Top Bottom