C# Dynamic List Name - c#

I need to create few list in c# but want to name those list dynamically according to some condition.
For example
List<string> x1= new List<string>();
List<string> x2 = new List<string>();
The name "x1" and "x2" would come at runtime (probably from some file or something). Is there any way to achieve this ?

Create Dictionary<string, List<string>>:
var dict = new Dictionary<string, List<string>>();
dict["x1"] = new List<string>();
You can replace "x1" with variable.

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] = "..";

Best way to hold sets of related elements dynamically added

I have a list of files, and the filenames for those files contain some characters then an underscore, then anything else like so:
test_123.txt
What I'm trying to do is loop through these files, pull out the 'prefix' (the characters up to but not including the _, add the prefix to a list if it's not already in the list, and then add the whole filename as an element of that prefix.
That might be confusing so here's an example:
List of file names:
A_ieie.txt
B_ldld.txt
C_test.txt
A_232.txt
B_file2.txt
C_345.txt
So I am looping through these files and get the prefix like so:
string prefix = fileName.Substring(0, fileName.IndexOf('_'));
Now, I check if that prefix is already in a list of prefixes, and if not, add it:
List<string> prefixes = new List<string>();
if (!prefixes.Contains(prefix))
{
prefixes.Add(prefix);
}
So here's the prefixes that would be added to that list:
A //not yet seen, add it to list
B //not yet seen, add it to list
C //not yet seen, add it to list
A //already seen, don't add
B //already seen, don't add
C //already seen, don't add
Okay the above is easy to do, but what about when I want to add the filenames that share a prefix to a list?
Since these are going to be dynamically added and could be anything, I can't make several lists before hand. I thought about have a List of lists, but is that really the best way to do this? Would a class be ideal?
The end goal of the above example would be something like :
[0][0] = A_ieie.txt //This is the 'A' list
[0][1] = A_232.txt
[1][0] = B_ldld.txt //This is the 'B' list
[1][1] = B_file2.txt
[2][0] = C_test.txt //This is the 'C' list
[2][1] = C_345.txt
Sounds like you want a Dictionary:
var list = new Dictionary<string, List<string>>();
The Key would be the "prefix" and the Value would be a list of strings (the filenames).
EDIT
If you want the list of filenames to be unique, perhaps a HashSet is a better option:
var list = new Dictionary<string, HashSet<string>>();
Sounds like you want a Dictionary>
Then, each list is referenced by a key integer (or use a string to "name" the list):
public Dictionary<string, List<string>> myBookList = new Dictionary<string, List<string>>();
private void addList(string listName, List<string> contents)
{
myBookList.Add(listName, contents);
//direct add
List<string> science_Fiction_Books = new List<string>();
myBookList.Add("Science Fiction", science_Fiction_Books);
myBookList["Science_Fiction"].Add("mytitle.txt");
myBookList["Science_Fiction"][0] = "My book title.txt";
string fileLocation = #"c:\mydirectory\mylists\myBookTitle.txt";
myBookList["Science_Fiction"].Add(System.IO.Path.GetFileName(fileLocation));
//etc.
}
You can use linq to achieve this.
List<string> List = new List<string>() { "A_ieie.txt", "B_ldld.txt", "C_test.txt", "A_232.txt", "B_file2.txt", "C_345.txt" };
Dictionary<string, List<string>> Dict = new Dictionary<string, List<string>>();
Dict = List.GroupBy(x => x.Split('_')[0]).ToDictionary(x => x.Key, x => x.ToList());
How about this:
var textFileNameList =
new List<string>{"A_ieie.txt","B_ldld.txt","C_test.txt",
"A_232.txt","B_file2.txt","C_345.txt"};
var groupedList = textFileNameList.GroupBy(t => t.Split('_')[0])
.Select( t=> new {
Prefix = t.Key,
Files = t.Select( file=> file).ToList()
}).ToList();

Create List with name from variable

Is it possible in C# to create a list and name it from a variable or similar?
Let's say I have a list with 10 rows in it:
a, b, c, d, e, f, g, h, i, j
Can I make 10 lists from this list, each having a name like one of the rows?
Something like
List<string> myList = new List<string>();
foreach (var line in myList)
{
List<string> line = new List<string>();
}
What I want is to make a few lists to store data in, but I won't know the names before the program runs so it needs to generate those dynamically.
Sounds like you want a Dictionary of List<string>s:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
dict.Add(line, new List<string>());
}
Now you can access each list based on the original string we used for the key:
List<string> aList = dict["a"];
You could try something like this:
var newList = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
newList.Add(line, new List<string>());
}
This will give you the data structures in which to store your new data and will allow you to reference them based on the names in the first list.
It seems that you want a Dictionary<String, List<String>> like this:
var data = myList
.ToDictionary(line => line, line => new List<string>());
And so you can
check if "variable" exists
if (data.ContainsKey("z")) {...}
address "variable"
data["a"].Add("some value");
add "variable"
data.Add("z", new List<string>());

Dictionary if Key exist append if not add new element C#

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");

.NET List<string> (call by reference?) with Dictionary objects

I have the following code snippet:
Dictionary<int, List<string>> likeListDict = new Dictionary<int, List<string>>();
List<string> lists = new List<string>();
lists.Add("hello");
lists.Add("world");
likeListDict.Add(1, lists);
lists.Clear();
lists.Add("foobar");
likeListDict.Add(2, lists);
At the likeListDict.Add(1, lists) part, the "hello" and "world" get added in to key 1. But once I do the lists.Clear(), and add in the key 2 to likeListDict, both key 1 and 2 now have "foobar". How do I stop this (call by reference) and make it call by value?
There is no concept of "call by reference" or "call by value". List<T> is a reference type, so whatever you do to a given reference will be visible anywhere in the program where that reference exists.
What you want to do is create a new list instead of calling lists.Clear();
Dictionary<int, List<string>> likeListDict = new Dictionary<int, List<string>>();
List<string> lists = new List<string>();
lists.Add("hello");
lists.Add("world");
likeListDict.Add(1, lists);
lists = new List<string>();
lists.Add("foobar");
likeListDict.Add(2, lists);
Make a second list, don't try to reuse the first list. You're storing a reference to lists in the Dictionary, so adding it twice results in the same reference being in your dictionary twice, so changes to your list are reflected in both entries in the dictionary.
Ex:
public static void Main()
{
var likeListDict = new Dictionary<int, List<string>>();
var lists = new List<string> {"hello", "world"};
likeListDict.Add(1, lists);
var secondList = new List<string> {"foobar"};
likeListDict.Add(2, secondList);
}

Categories