Create list<string> dynamically - c#

I want to create a list in a button click event...every time the button is clicked a new list should be created having different name than the previous one...
Can anyone please help me out...I'm stuck on it...

Better create List<List<string>>
List<List<string>> lls = new List<List<string>>();
Button_Click()
{
List<string> str = new List<string>();
for (int i = 0; i < sub.Count; i++)
{
if (checkbx[i].Checked == true)
{
str.Add(checkbx[i].Text);
}
}
lls.Add(str);
}
hence their names would be lls[0], lls[1],... etc

List objects doesn't have names, variables have names.
Creating variables dynamically is mostly useless, especially in compiled languages. What you want is a collection where you can store multiple lists, e.g. a list of lists:
public List<List<string>> str = new List<List<string>>();
public void check() {
List<string> subs = new List<string>();
for (int i = 0; i < sub.Count; i++) {
if (checkbx[i].Checked) {
subs.Add(checkbx[i].Text);
}
}
str.Add(subs);
}

Use a dictionary of lists where the key is the list name and the value is the list itself.
//Defining Dictionary
Dictionary<string, List<string>> ListDict = new Dictionary<string, List<string>>();
//Add lists in Dictionary
OnClick(string listname)
{
ListDict.Add(listname, new List<string>());
}
//Add values in List
ListDict[listname].Add("xyz");

Related

Creating a new list by incrementing two separate lists

I'm trying to create a new list from two separate lists like so:
List 1 (sCat) = MD0, MD1, MD3, MD4
List 2 (sLev) = 01, 02, 03, R
Output-->
MD0-01
MD0-02
MD0-03
MD0-R
MD1-01
MD1-02
MD1-03
MD1-R
MD3-01
MD3-02
MD3-03
MD3-R
etc...
I would like to know if there is a function that would produce the results above. Ultimately, I would like the user to provide List 2 and have that information added to List 1 and stored as a new list that I could call later.
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<string> sCat = new List<string>();
// add Categories for the Sheets
sCat.Add("MD0");
sCat.Add("MD1");
sCat.Add("MD3");
List<string> sLev = new List<string>();
// add Levels for the Project
sLev.Add("01");
sLev.Add("02");
sLev.Add("03");
sLev.Add("R");
for (int i = 0; i < sCat.Count; i++)
{
// I am getting stuck here.
// I don't know how to take one item from the sCat list and
// add it to the sLev List incrementally.
Console.WriteLine(sCat[i],i);
}
Console.ReadLine();
}
}
Combine the values of all the elements selected from the first collection with the elements contained in the other collection:
var combined = sCat.SelectMany(s => sLev.Select(s1 => $"{s}-{s1}")).ToList();
Which is like iterating the two collections in a nested for/foreach loop, adding each combined element to a new List<string>:
List<string> combined = new List<string>();
foreach (var s1 in sCat)
foreach (var s2 in sLev) {
combined.Add(s1 + "-" + s2);
}
You can replace your for loop with following:
foreach(var sCatValue in sCat)
{
foreach(var sLevValue in sLev)
{
Console.WriteLine($"{sCatValue}-{sLevValue}");
}
}
private static void Main()
{
List<string> sCat = new List<string>();
// add Categories for the Sheets
sCat.Add("MD0");
sCat.Add("MD1");
sCat.Add("MD3");
List<string> sLev = new List<string>();
// add Levels for the Project
sLev.Add("01");
sLev.Add("02");
sLev.Add("03");
sLev.Add("R");
string dash = "-";
List<string> newList = new List<string>();
for (int i = 0; i < sCat.Count; i++)
{
for (int j = 0; j < sLev.Count; j++)
{
newList.Add(sCat[i] + dash + sLev[j]);
}
}
foreach (var item in newList)
{
Console.WriteLine(item);
}
Console.ReadLine();
}

I am trying to create multiple arrays/dictionaries in C# using a for loop

I am trying to create multiple arrays/dictionaries in C# using a for loop. I can declare them individually, but it's not clean.
Here is my code:
string[] names = ["dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"];
for (int i = 0; i <= names.Length; i++)
{
string building = names[i];
Dictionary<long, int> building = new Dictionary<long, int>();
}
I am trying to use the names stored in the names array to iteratively create arrays. Visual Studio doesn't accept "building" as it is already declared. Any suggestion would be greatly appreciated. Thank you!
There's not a way in C# to create dynamically-named local variables.
Perhaps you want a dictionary of dictionaries?
string[] names = ["dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"];
var buildings = new Dictionary<string,Dictionary<long, int>>();
for (int i = 0; i <= names.Length; i++) {
buildings[names[i]] = new Dictionary<long, int>();
}
//... meanwhile, at the Hall of Justice ...
// reference the dictionary by key string
buildings["dSSB"][1234L] = 5678;
You can try it like this
string[] names = {"dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB"};
Dictionary<string, Dictionary<long, int>> buildings = new Dictionary<string, Dictionary<long, int>>();
for (int i = 0; i <= names.Length -1; i++)
{
buildings[names[i]] = new Dictionary<long, int>();
buildings[names[i]].Add(5L, 55);
}
//Here you can get the needed dictionary from the 'parent' dictionary by key
var neededDictionary = buildings["dSSB"];
Cheers
If you're simply trying to make a dictionary, and put stuff in it:
Dictionary<int, string> buildings = new Dictionary<int, string>();
string[] names = { "dSSB", "dGEN", "dLYM", "dLUD", "dGGC", "dMAC", "dMMB" };
for (int i = 0; i < names.Length; i++)
{
buildings.Add(i, names[i]);
}
foreach (KeyValuePair<int, string> building in buildings)
{
Console.WriteLine(building);
}

Creating a List<String> in Android Xamarin

I'm building an android application where I need to create a simple list of String items, which i will then add a specific control for each item in the list.
This is the list I want to create:
List<String> projects = new List<String>(); // How?
The code I was trying:
String projects = new string[] { "hey","yo","app","xamarin","c","xaml" };
I need to count the items, something like this:
int amount = projects.Count(); // Can I do this?
Then adding the controls for each item in the list
// Add the tiles, one by one
for (int i = 0; i < amount; i++)
{
// Inflate the tile
var tile = LayoutInflater.Inflate (Resource.Layout.Tile, null);
// Set its attributes
tile.FindViewById<TextView> (Resource.Id.projectName).Text = currentProject;
// Add the tile
projectScrollView.AddView (tile);
}
"currentProject" string is retrieved from SharedPreferences, just haven't got that far yet
var projects = new List<String>() { "hey","yo","app","xamarin","c","xaml" };
if you are using the array to store what values you want in your list use the foreach
List<string>project = new List<string>();
string[] projects = { "hey","yo","app","xamarin","c","xaml" };
foreach(string str in projects)
{
project.Add(str);
}
for (int i = 0; i < projects.Length; i++)
{
// Inflate the tile
var tile = LayoutInflater.Inflate (Resource.Layout.Tile, null);
// Set its attributes
tile.FindViewById<TextView> (Resource.Id.projectName).Text = currentProject;
// Add the tile
projectScrollView.AddView (tile);
}
// you can get items from your list by using project.Count, your List<string> instead of projects.Length your array and take information from your list and output your tiles that way
To initialize a List<string> with collection initializer use the below syntax.
List<String> projects = new List<String>(){"hey","yo","app","xamarin","c","xaml"};
Count is not a method it is a property. You need property syntax.
int amount = projects.Count;
int amount = projects.Length;
that is how you can set the value of the int. It doesnt appear that you are populating your list with that code.

Randomly place images in multiple Image controls

I am creating a simple "Pairs" game in WPF. I have 12 Image controls on MainWindow. What I need to do, is to use OpenFileDialog to select multiple Images (can be less then all 6) and then randomly place them into Image controls. Each picture should appear twice. How would I be able to achieve this? I am stuck here for a while and only have following code at the moment. I am not asking for a solution, I only need a few pointers on how to deal with this. Thank you.
> public ObservableCollection<Image> GetImages()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = true;
ObservableCollection<Image> imagesList = new ObservableCollection<Image>();
if (dlg.ShowDialog() == true)
{
foreach (String img in dlg.FileNames)
{
Image image = new Image();
image.Name = "";
image.Location = img;
imagesList.Add(image);
}
}
return imagesList;
}
There are many ways to achieve your required results. A good way would be to use the Directory.GetFiles method, which will return a collection of string file paths:
string [] filePaths = Directory.GetFiles(targetDirectory);
You can then use a method to randomise the order of the collection. From the C# Shuffle Array page on DotNETPerls:
public string[] RandomizeStrings(string[] arr)
{
List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
// Add all strings from array
// Add new random int each time
foreach (string s in arr)
{
list.Add(new KeyValuePair<int, string>(_random.Next(), s));
}
// Sort the list by the random number
var sorted = from item in list
orderby item.Key
select item;
// Allocate new string array
string[] result = new string[arr.Length];
// Copy values to array
int index = 0;
foreach (KeyValuePair<int, string> pair in sorted)
{
result[index] = pair.Value;
index++;
}
// Return copied array
return result;
}
Then add your duplicate file paths, re-randomise the order again and populate your UI property with the items:
string[] filePathsToUse = new string[filePaths.Length * 2];
filePaths = RandomizeStrings(filePaths);
for (int count = 0; count < yourRequiredNumber; count++)
{
filePathsToUse.Add(filePaths(count));
filePathsToUse.Add(filePaths(count));
}
// Finally, randomize the collection again:
ObservableCollection<string> filePathsToBindTo = new
ObservableCollection<string>(RandomizeStrings(filePathsToUse));
Of course, you could also do it in many other ways, some easier to understand, some more efficient. Just pick a method that you feel comfortable with.

Remove Element From Array by String (text) instead of Index

I want to remove the element form the array. Actually I don't know the the index of the element and want to remove through it's value. I have tried a lot but fail. This is the function which i used to add element in the Array
string [] Arr;
int i = 0;
public void AddTOList(string ItemName)
{
Arr[i] = ItemName;
i++;
}
And I want to remove the element by the value. I know the below function is wrong but I want to explain what I want:
public void RemoveFromList(string ItemName)
{
A["Some_String"] = null;
}
Thanks
If you want to remove items by a string key then use a Dictionary
var d = new Dictionary<string, int>();
d.Add("Key1", 3);
int t = d["Key1"];
Or something like that.
Array has a fixed size, which is not suitable for your requirement. Instead you can use List<string>.
List<string> myList = new List<string>();
//add an item
myList.Add("hi");
//remove an item by its value
myList.Remove("hi");
List<string> list = new List<string>(A);
list.Remove(ItemName);
A = list.ToArray();
and #see Array.Resize
and #see Array.IndexOf
You can iterate through every value in array and if found then remove it. Something like this
string[] arr = new string[] { "apple", "ball", "cat", "dog", "elephant", "fan", "goat", "hat" };
string itemToRemove = "fan";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == itemToRemove)
{
arr[i]=null;
break;
}
}

Categories

Resources