好的所以我有这个包含3个项目的Hashset,我想对它应用一些逻辑,这样我就可以为hashset中的每个项目附加一些预定义的3个值
例如,
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}
我想要的输出是:
unique strings associating "RedAlpha", "YellowBeta", "bluegamma"
例如s1 =“RedAlpha”,s2 =“YellowBeta”,s3 =“bluegamma”;
然后我想稍后对它们中的每一个应用一些不同的逻辑但是我猜这是另一回事
我的尝试代码
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++;
}
我的其他尝试代码,
foreach(string strr in hs)
{
string s = strr + str[index];
s = s + ","
index++;
}
s.split(",");
答案 0 :(得分:1)
将它们列入清单:
int index = 0;
var list = new List<string>();
foreach(string strr in hs)
{
list.Add(strr + str[index]);
index++;
}
Console.WriteLine(list[0]); //RedAlpha
答案 1 :(得分:1)
如果要将两个集合合并在一起并对它们执行某些操作,请使用Zip方法。有关Zip方法的说明,请参阅this answer。
以下是如何实现您的需求:
0
如果你想要一本字典,它也是直截了当的:
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();