C# Declare multiple dynamically named variables [duplicate] - c#

This question already has answers here:
How do I name variables dynamically in C#?
(9 answers)
Closed 8 years ago.
I'm not sure of the wording of what I'm looking for so I apologize if this has been answered since I'm new to C#.
What I'm trying to do is create multiple dynamically-named Lists based off of "i".
A code snippet would like this:
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];
}
I was hoping it would create new Lists named:
user1
user2
user3
etc.
Update Sorry all for being so confusing. You guys swarmed with answers! Let me be more specific. I'm practicing string output from a Console application such as using "PsExec \localhost qwinsta". The output would look like this:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
>console mariob 1 Active
rdp-tcp 65536 Listen
Each line is stored in the List "infoForUserSessions" so the data looks like:
infoForUserSessions[0] = services 0 Disc
infoForUserSessions[1] = >console mariob 1 Active
infoForUserSessions[2] = rdp-tcp 65536 Listen
I then have code to pick out the important text out of each array index:
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);
}
}
I'm still working out the logic but I figured I wanted the output to be something dynamic based off of two factors:
How many "users" (strings) were stored in the List infoForUserSessions
Individual user arrays/Lists that have their own index values of:
.
user1[0] = "services";
user1[1] = "0";
user1[2] = "Disc";
user2[0] = ">console";
user2[1] = "mariob";
user2[2] = "1";
user2[2] = "Active";

Don't try to use dynamically named variables. That's simply not how variables work in C#.
Use an array of lists:
List<string>[] user = new List<string>[infoForUserSessions.Count];
for (int i = 0; i < infoForUserSessions.Count; i++) {
user[i] = new List<string>();
}
If the number of sessions can change, you would use a List<List<string>> instead, so that you can add lists to it when you add items to the infoForUserSessions list.

You can use Dictionary<String, List<string>>
Dictionary associate a key to a value, like an physical Dictionary book.
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>());
}
Here is an exemple how to use 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"];

Related

How to use items of an array as names for other variables c#

I have a list of names in an array and i would like to use these names to assign them to new lists like bellow:
var list = new string[]{"bot1","bot2","bot3"};
List<string> list[0] = new List<string>();
but i am getting the error: a local variable or function named 'list' is already defined in this scope.
is there a work around !!?
your input will be greatly appreciated.
I think you can store your bots in dictionary:
var bots = new Dictionary<string,List<string>>();
bots[name] = new List<string>();
bots[name].Add("some str");
If you only need a integer as key than you can also use this solution.
List<List<string>> list = new List<List<string>>();
list.Add(new List<string>{ {"A"} });
list[0][0] = "..";

Create variable which will be named with listValue

I'm having a little problem with creating variable which will be named by list value.
Here is an example with what I want.
for (int i = 0; i < list.Count; i++)
{
//here I want to create variable
//which will be named with list[i]
}
So if list has 2 elements eg.
list[0] = "testName"
list[1] = "andAnotherOne"
I want to create 2 variables,
one of them is named testName and the second one andAnotherOne
Can you help me complete it?
I believe you need a Dictionary as said by TaW. This allows you to have the value same as the index.
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("foo","foo"); //index,value of index
if(dictionary.ContainsKey["foo"])
{
string value = dictionary["foo"];
Console.Write(value);
}
I hope I understood your question.
Just create A List<string> names = new List<string>();
for (int i = 0; i < 5; i++)
{
names.Add("sample" + i);
}
EDIT:
If you want to refer with names then use a dictionary like below,
Dictionary<string, string> myvalues = new Dictionary<string, string>();
You can use dynamic and ExpandoObject:
var variables = new List<string> { "variableOne", "variableTwo" };
dynamic scope = new ExpandoObject();
var dictionary = (IDictionary<string, object>)scope;
foreach (var variable in variables)
dictionary.Add(variable, "initial variable value");
Console.WriteLine(scope.variableOne);
Console.WriteLine(scope.variableTwo);
In C#, variables are all statically declared. I think you can't do that. Maybe you can try with the reflection but I think it won't able you to do what you want.
Some things I found that could interest you :
string to variable name
Convert string to variable name

ASP.NET add item to array

I have this array defined:
string[] emailAddress = {};
What I am trying to do is add items to this array like so:
emailAddress[] = de.Properties["mail"][0].ToString();
and I get a cannot convert string to array error. How do I add an item to an array?
string[] emailAddress = new string[1]; // initialize it to a length of 1
emailAddress[0] = de.Properties["mail"][0].ToString(); // assign the string to position 1
If you do not know the length at runtime then use a generic List and convert it afterwards.
var emailAddress = new List<string>();
emailAddress.Add(de.Properties["mail"][0].ToString());
var myArray = emailAddress.ToArray(); // create an array from the list
I recommend you read this article on how to work with arrays in c# (or some other tutorial).
https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
Based on your comment that it has to be an array and can't be a List, this might be what you need.
Instantiate the array with a specific length. Something like this
string[] emailAddress = new string[emailAddressde.Properties["mail"].Length];
Then you can loop through with something like
for (var i = 0; i < de.Properties["mail"].Length; i++)
emailAddress[i] = de.Properties["mail"][i].ToString();
to populate your emailAddress array.
You have to initialize your array first with a fixed size:
string[] emailAddress = new string[5]; // array with 5 items
and then you can add items like this:
emailAddress[0] = de.Properties["mail"][0].ToString();
But consider if somehow possible using a List<string> which is much more flexible.
You need to reference a location in your array, what you are trying to do is assign your value as the array.
emailAddress[0] = de.Properties["mail"][0].ToString();
If you know how big your array will be then you can init the array to a static size. For example if you know that the array of email will only every be 2 items (index 0 and 1) then you can init the array to that size like this
string[] emailAddress = string[2];
if the items in the array are unknown (how many email addresses) the you should using something else like
List emailAddresses = new List();
So something like this:
List<string> emailAddresses = new List<string>();
emailAddresses.Add("youremail#mail.com");
emailAddresses.ToArray();

How to edit object array adding new data to set in C#

List<ChartView> data = new List<ChartView>();
var chartData = new object[data.length+1];
chartData[0] = new object[]
{
"Chart",
"Standard",
"BL"
};
int j = 0;
foreach (var i in data)
{
j++;
chartData[j] = new object[]
{
i.particulars,
i.originalDocuments,
i.filingOfEntries,
i.assessmentOfDuties,
i.paymentOfDuties,
i.releasing,
i.gatePass,
i.delivery
};
}
How can i add new data in object without deleting the old data. In the above code charttData[0] have 3 value Chart,Standard,BL. I need to add new string to the set of object. It should become Chart,Standard,BL,Sample.
I am working on dynamic line chart like this. The number of lines must be dynamic it could be 1,2 or morethan 10.
Please note that this question is not about Add new item in existing array in c#.net (which was earlier suggested as duplicate).
I try my best to understand your question, base on my understanding what your goal is to add new type of graph in your "object[] bla bla bla..." and each type of graph can use the content of data?
If my understanding is correct, I suggest to use Dictionary instead of confusing object array, by using Dictionary you can easily add new type of graph just like my example below:
List < ChartView > data = new List < ChartView > ();
Dictionary < string, List < ChartView >> graphType = new Dictionary < string, List < ChartView >> () {
{
"Chart", data
}, {
"Standard", data
}, {
"BL", data
}
}; // First you only have 3 kind of graphs.
grapType.Add("Sample", data); // this will allow you to add another graph named sample.
Note: This is just example how to use dictionary.

I want to return a sublist of object and Total size of the Original List

I want to return a sublist of object and Total size of the Original List.
in this case can i use MAP .
Example :-
Map<Integer,String> sample(){
List<String> list = new ArrayList<String>(0);
for(i=0;i<50;i++)
list.add(i+"");
List<String> sublist = list.sublist(0,10);
Integer totalsize = list.size();
Map<Integer,String> map = new Hashmap<Integer,List>(0);
map.put(totalsize,sublist);
return map;
}
otherwise can i return one POJO Object fro returning these information to calling function.
I need a performance wise guidance on this .
If you are using C#, you can use the ArraySegment<T> structure. It contains a reference of the original array too. You can find the details here in msdn
You need a Map to store the sublist and size of the original list with two different keys, here is the code in java to meet the req...
Map<Integer, String> sample() {
Map map = new HashMap();
List<String> list = new ArrayList<String>(0);
for ( int i = 0; i < 50; i++)
list.add(i + "");
List<String> sublist = list.subList(0, 10);
Integer totalsize = list.size();
map.put("sublist", sublist);
map.put("original_list_length", totalsize);
return map;
}

Categories