0

Okay So I have this Hashset that contains 3 items and I want to apply some logic on it such that I am able to append some predefined 3 values for the each item present inside the hashset

for example,

HashSet<string> hs = new HashSet<string>(); //it could be string or some other class object
hs.add("Red");
hs.add("Yellow");
hs.add("Blue");

//Some predefined values for those strings that I want to append to them
string[] str = {Alpha, Beta, Gamma}

The output I desire is:

unique strings associating "RedAlpha", "YellowBeta", "bluegamma" 

for example s1 = "RedAlpha", s2 = "YellowBeta", s3 = "bluegamma";

I then want to apply some different logic to each of them later but then I guess that is a different thing

My Tried code

int count = 1;
int index = 0;
string s = "";
foreach(string strr in hs)
{

 string s + count = strr + str[index]; // I don't know how to make new unique string
 count++;
 index++;
}

My other Tried Code,

   foreach(string strr in hs)
{

 string s = strr + str[index]; 
 s = s + ","
 index++;
}

s.split(",");
Shad
  • 1,185
  • 1
  • 12
  • 27
  • Stop. Asking questions and dumping the answers into your program will not make you a good programmer. Take a step back and make sure you understand the things in the code you are already using. Then when you ask a question and are introduced to something new, study what you've been shown. Don't just throw together bits of code like they are magical incantations in some language no one understands. – Ben Voigt Feb 09 '18 at 02:47
  • @BenVoigt I am sorry sir. – Shad Feb 09 '18 at 02:48
  • 1
    No reason to apologize to me. I just want to help you improve faster, by pointing out that you already had the piece you needed (arrays). – Ben Voigt Feb 09 '18 at 02:50

2 Answers2

1

Put them in a list:

int index = 0;
var list = new List<string>();
foreach(string strr in hs)
{
    list.Add(strr + str[index]);
    index++;
}

Console.WriteLine(list[0]); //RedAlpha
Backs
  • 24,430
  • 5
  • 58
  • 85
1

When you want to merge 2 collection together and perform some operation on them, use the Zip method. See this answer for an explanation of Zip method.

Here is how to achieve what you need:

HashSet<string> hs = new HashSet<string>();
hs.Add("Red");
hs.Add("Yellow");
hs.Add("Blue");

string[] str = { "Alpha", "Beta", "Gamma" };
List<KeyValuePair<string, string>> kvps = 
    hs.Zip(str, (left, right) => new KeyValuePair<string, string>(left, right))
    .ToList();

If you want a dictionary, it is straight forward as well:

Dictionary<string, string> kvps = 
    hs.Zip(str, (left, right) => new { left, right })
    .ToDictionary(x => x.left, x.right);
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64