我不确定我正在寻找什么的措辞,所以如果我已经回答了这个问题,我很抱歉,因为我是C#的新手。
我要做的是根据“i”创建多个动态命名的列表。
代码段是这样的:
List<string> infoForUserSessions = new List<string>();
// Code that adds data to infoForUserSessions
for (int i = 0; i < infoForUserSessions.Count; i++){
// I want to initialize multiple List variables based off of how many users were found in my "infoForUserSessions" List.
List<string> user[i];
}
我希望它会创建名为的新列表:
用户1
用户2
用户3
等
更新抱歉所有这些令人困惑。你们蜂拥而至!让我更具体一点。我正在练习来自Console应用程序的字符串输出,例如使用“PsExec \ localhost qwinsta”。输出看起来像这样:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
>console mariob 1 Active
rdp-tcp 65536 Listen
每一行都存储在List“infoForUserSessions”中,因此数据如下所示:
infoForUserSessions[0] = services 0 Disc
infoForUserSessions[1] = >console mariob 1 Active
infoForUserSessions[2] = rdp-tcp 65536 Listen
然后我有代码从每个数组索引中挑选出重要文本:
string[] tempStringArray;
List<string> allUsersAndIDs = new List<string>();
char[] delimiters = new char[] { ' ' };
foreach (string line in infoForUserSessions)
{
tempStringArray = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < tempStringArray.Length; i++)
{
// This is where I was thinking of some logic to create a new array for each user so I could store the separate parts of a string into this new array
// Something like (which would be from the Lists above in my original message--this is based off of how many users were stored in the original infoForUserSessions List:
// user1.Add(i);
}
}
我仍在研究逻辑,但我想我希望输出是基于两个因素的动态:
user1[0] = "services";
user1[1] = "0";
user1[2] = "Disc";
user2[0] = ">console";
user2[1] = "mariob";
user2[2] = "1";
user2[2] = "Active";
答案 0 :(得分:4)
不要尝试使用动态命名的变量。这根本不是C#中变量的工作原理。
使用列表数组:
List<string>[] user = new List<string>[infoForUserSessions.Count];
for (int i = 0; i < infoForUserSessions.Count; i++) {
user[i] = new List<string>();
}
如果会话数量可以更改,您可以使用List<List<string>>
代替,以便在向infoForUserSessions
列表添加项目时向其添加列表。
答案 1 :(得分:1)
您可以使用Dictionary<String, List<string>>
Dictionary将键与值相关联,就像物理词典书一样。
Dictionary<String, List<string>> myDict = new Dictionary<String, List<string>>();
for (int i = 0; i < infoForUserSessions.Count; ++i){
myDict.add("user" + i, new List<string>());
}
这是一个如何使用Dictionary的例子:
Dictionary<String, String> myDict = new Dictionary<String, String>();
//Line below will add both KEY and a VALUE to the dictionary, BOTH are linked one to eachother
myDict.add("apple", "Apple is a brand");
//This above line return "Apple is a brand"
myDict["apple"];