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
Related
I have the following declaration and I need to get the first element from the list using key. Then after assigning that value to some variable again I need to remove that value alone from that list.
Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
For Example:
List<string> teamMembers = new List<string>();
teamMembers.Add("Country1Player1");
teamMembers.Add("Country1Player2");
teamMembers.Add("Country1Player3");
data.Add("Country1",teamMembers);
teamMembers = new List<string>();
teamMembers.Add("Country2Player1");
teamMembers.Add("Country2Player2");
teamMembers.Add("Country2Player3");
data.Add("Country2",teamMembers);
From the above dictionary, I need to select the Country1 's first element Country1Player1 and assign to some variable. After that I need to remove that value alone from the value list.
Expected output:
If I pass key as 'Country1' then it should give me Country1Player1 and that value needs to be removed the data dictionary. Key Country1 should contain only Country1Player2 & Country1Player3 in the list of values.
string firstTeamMember = null;
if (data.TryGetValue("Country1", out List<string> list) && list?.Any() == true)
{
firstTeamMember = list[0];
list.RemoveAt(0);
}
You could try sth like this:
if(data.TryGetValue("Country1", out var values))
{
var firstValue = values?.FirstOrDefault();
data["Country1"] = data["Country1"]?.Skip(1).ToList();
}
How would I compare these 2 dictionaries and return only the values missing?
The GetFileListFromBlob() function gets all file names and I'd like to know what is missing from the db.
Or is there a better way to get the missing values from these objects? Should I use different key/ value?
Dictionary<int, string> databaseFileList = new Dictionary<int, string>;
Dictionary<int, string> blobFileList = new Dictionary<int, string>;
int counter = 0;
foreach (string f in GetFileListFromDB())
{
counter++;
databaseFileList.Add(counter, f );
}
counter = 0;
foreach (string f in GetFileListFromBlob())
{
counter++;
blobFileList.Add(counter, f);
}
// How to compare?
Thank you
A HashSet<T> might be what you want (instead of a Dictionary<K,V>) - take this example:
var reference = new HashSet<string> {"a", "b", "c", "d"};
var comparison = new HashSet<string> {"a", "d", "e"};
When you now call ExceptWith on the reference set ...
reference.ExceptWith(comparison);
... the reference set will contain the elements "b" and "c" that do not exist in the comparison set. Note however that the extra element "e" is not captured (swap the sets to get "e" as the missing element) and that the operation modifies the reference set in-place. If that isn't wished for, the Except LINQ operator might be worth investigating, as was already mentioned in another answer.
The way I see it, you don't need counters at first (you can add them later).
You can use System.Collections.Generic.List<> type to go on.
List<int, string> databaseFileList = new List<string>(GetFileListFromDB());
List<int, string> blobFileList = new List<string>(GetFileListFromBlob());
//some code
Now if you want to get all items in both lists you can simply use Concat(...) method to unify them and then use Distinct() method to remove duplicate items:
List<string> allItems = databaseFileList.Concat(blobFileList).Distinct();
Now use Except(...) method to compare collections:
var missingItems1 = allItems .Except(databaseFileList);
//or
var missingItems1 = allItems .Except(blobFileList);
//or
//some other code
private void CompareDictionary()
{
var databaseFileList = new Dictionary<int, string>();
var blobFileList = new Dictionary<int, string>();
databaseFileList.Add(300, "apple");
databaseFileList.Add(500, "windows");
databaseFileList.Add(100, "Bill");
blobFileList.Add(100, "Bill");
blobFileList.Add(200, "Steve");
var result = databaseFileList.Where(d2 => !blobFileList.Any(d1 => d1.Key == d2.Key)).ToList();
}
I am having
Dictionary<String, List<String>> filters = new Dictionary<String, List<String>>();
which is having values like country = us. till now I am able to add it when key is not repeated. now when key country is repeated. it is showing that the key is already present.
what I want is How to add multiple values in the same key. I am not able to do it. Please suggest something.
for (int i = 0; i < msgProperty.Value.Count; i++)
{
FilterValue.Add(msgProperty.Value[i].filterValue.Value);
filterColumn = msgProperty.Value[i].filterColumnName.Value;
filters.Add(filterColumn, FilterValue);
}
what I want
country = US,UK
The different types of all your variables are a bit confusing, which won't help you writing the code. I'm assuming you have a Dictionary<string, List<string>> where the key is a "language" and the value is a list of countries for that language, or whatever. Reducing a problem to a minimal set that reproduces the issue is very helpful when asking for help.
Anyway assuming the above, it's as simple as this:
Try to get the dictionary["somelanguage"] key into existingValue.
If it doesn't exist, add it and store it in the same variable.
Add the List<string> to the dictionary under the "somelanguage" key.
The code will look like this:
private Dictionary<string, List<string>> dictionary;
void AddCountries(string languageKey, List<string> coutriesToAdd)
{
List<string> existingValue = null;
if (!dictionary.TryGetValue(languageKey, out existingValue))
{
// Create if not exists in dictionary
existingValue = dictionary[languageKey] = new List<string>()
}
existingValue.AddRange(coutriesToAdd);
}
You simply need to check whether the value exists in the dictionary, like this:
if (!filters.ContainsKey("country"))
filters["country"] = new List<string>();
filters["country"].AddRange("your value");
Assuming you are trying to add value for key country
List<string> existingValues;
if (filters.TryGetValue(country, out existingValues))
existingValues.Add(value);
else
filters.Add(country, new List<string> { value })
If your values is List<string>
List<string> existingValues;
if (filters.TryGetValue(country, out existingValues))
existingValues.AddRange(values);
else
filters.Add(country, new List<string> { values })
Make use of IDictionary interface.
IDictionary dict = new Dictionary<String, List<String>>();
if (!dict.ContainsKey("key"))
dict["key"] = new List<string>();
filters["key"].Add("value");
Is it possible to use a variable to access 2 variables without naming another variable?
For example, to:
LOG.dig.CNLog = 7;
LOG.value.CNLog = 17;
I would like to use something like this
string a = "dig";
string b = "value";
LOG.[a].CNLog = 7;
LOG.[b].CNLog = 17;
It's possible to use this? If yes what is the correct format?
Thanks
You can use a Dictionary<string, int>. An example:
var dict = new Dictionary<string, int>();
dict.Add("test", 1);
var testVal = dict["test"];
You can do that by using a Dictionary<TKey, TValue>.
A dictionary is a collection of keys and values. In your case you probably would like to use a Dictionary<string, LogClass> then you can have something like this:
Assuming LogClass is your class...
public class LogClass
{
public int CNLog { get; set; }
}
string a = "dig";
string b = "value";
dictionary[a].CNLog = 7;
dictionary[b].CNLog = 17;
But of course before doing that you would have to say what is the value that goes into dictionary[var].
dictionary[a] = new LogClass();
That is how you would use it, hopefully you will be able to adapt this solution to your code.
And you can check out a video that explains step-by-step very slowly and clearly how to work with it on Microsoft Virtual Academy: C# Fundamentas at 22:00.
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"];