Having a new list<> in each for loop iteration - c#

I am trying to having a new list added on every for loop iteration. I have the following code:
for (int i = 0; i < torni.Length; i++)
{
List<string> torni+i = // STUCK HER
}
Listnames should be like torni0, torni1, torni2 ......
Would really appreciate your assistance. Thanks!!

One way of doing this that would be slightly different would be to make a list of lists and then each index would be a discrete list.
You can't dynamically generate variable names in c#
like this:
tornis = new List<List<String>>()
for (int i = 0; i < torni.Length; i++)
{
tornis.append(new List<String>())
}
Alternatively as DanH Points out a dictionary of lists
tornis = new Dictionary<String,List<String>()
for (int i = 0; i < torni.Length; i++)
{
tornis.add("torni" + i, new List<String>())
}
This will give you a dictionary with the keys of the convention you want and a list of lists.

If you need each list only for the duration of a single loop iteration, then you don't need different list names:
for (int i = 0; i < torni.Length; i++)
{
List<string> temporaryList = new List<string>();
// use the list here
}

Related

How to swap values from one generic list to another

I have 2 T Lists e.g:
list1 with attributes {ID, Name, Email}
list2 is of the same type
What I want is to be able to replace list1 ID values with ID values from list2, not affecting any Name and Email values
Eventually I would be even happier if I could have List list2 values to replace ID values from list1.
Thanks a lot.
I have tryed using for loop but it does not seem to work:
`for (int i = 0; i < list1.Count; i++)
{
list1[i].GroupID =list2[i].GroupID;
}`
for (var i = 0; i < list1.Count; i++)
{
var temp = list1[i].GroupID;
// swap
list1[i].GroupID = list2[i].GroupID;
list2[i].GroupID = temp;
}
Or Use tuple.
for (var i = 0; i < list1.Count; i++)
{
// swap
(list1[i].GroupID, list2[i].GroupID) = (list2[i].GroupID, list1[i].GroupID)
}
Both methods must have the same count of list1 and list2.

Cannot convert from 'string' to 'system.collections.generic.list string'

I have the two list
nested list of string, and
list in string
In index list, I want to add linesOfContentwith a common value and in-between i want to add separate string ":".
For that i write a code, but, I face a problem "cannot convert from 'string' to 'system.collections.generic.list string'". How to solve this.
int common = 10;
List<List<string>> index = new List<List<string>>();
List<int> linesOfContent = new List<int>();
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
linesOfContent.Add(i+":"+common);
}
index.Add(linesOfContent);
}
Expected Output:
index[0][0] = 0:10
index[0][1] = 1:10
index[0][2] = 2:10
...
...
A List of Lists of string should contain Lists of string, not Lists of int.
int common = 10;
List<List<string>> index = new List<List<string>>();
List<string> linesOfContent = new List<string>();
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
linesOfContent.Add(i.ToString() +":"+common.ToString());
}
index.Add(linesOfContent);
}
Each item in your index list is a List<string>. When you try to add an item, it should be a List. However, you're trying to add a string to it, linesOfContent+":"+common is considered a string.
Solution:
Linq's Select Method (aka Projection) can be used to transform each element inside a sequence:
index.Add(linesOfContent.Select(x=> x.ToString() + ":" + common).ToList());
Be aware that the way you're constructing your loops results in some duplicate records.
Here's the code, without the foreach loops, instead it uses Enumerable.Range:
linesOfContent.AddRange(Enumerable.Range(0, 5).Select(i => i.ToString() + ":" + common.ToString()).ToArray());
index.Add(linesOfContent);

Frequency for duplicate items in a list C#

I'm on VS Windows Forms Application and I'm NOT using any other form of coding (e.g. linq) - just the basic style of coding which goes like this;
List<string> brandList = new List<string>();
//brand items are added to the list
//go through list
for(int i = 0; brandList.Count; i++)
{
if(brandList[i]== "BrandName1")
{
//count for that brandName
}
}
What I want to know is how to I get the count for how many times a brand has occurred in the list?
This code will not need to be case sensitive either because it is being read in from a file..
If you don't want/can't use LINQ you could use a Dictionary<string, int>:
Dictionary<string, int> dict = new Dictionary<string, int>();
for(int i = 0; brandList.Count; i++)
{
string brand = brandList[i];
int count = 1;
if(dict.ContainsKey(brand))
count = dict[brand] + 1;
dict[brand] = count;
}
Now you have all brands as key and their counts as value.
I really don't see the problem because your code is already have the solution if I understand correctly the question. You go through the elements, if the current element is the element to count you increment a variable.
const string BRAND = "BrandName1";
int count = 0;
foreach (string brand in brandList)
{
if (string.Compare(brand, BRAND, true))
{
count++;
}
}
Obviously you can use for (int i = 0; i < brandList.Count; i++) and brandList[i] instead of foreach, but it's more like C#.
How about this:
List<string> brandList = new List<string>();
//brand items are added to the list
//sort list to get number of occurences of each entry
brandList.Sort();
var occurences = new List<KeyValuePair<string, int>>();
//go through list
var numBrand = 1;
for (int i = 0; i < brandList.Count-1; i++)
{
if (string.Equals(brandList[i + 1], brandList[i]))
{
numBrand++;
}
else
{
occurences.Add(new KeyValuePair<string, int>(brandList[i], numBrand));
numBrand = 1;
}
}
var highestCount = occurences.OrderBy(o => o.Value).ToList()[0].Key;
It might skip the last entry if that is a single occurences but then that's not the highest anyway.
Would that do the trick for you?

Do you always have to start at the index zero when writing a 2D list?

I want to fill in a 2Dlist, but start at the third position [2]. Is this somehow possible?
A short code for understanding what i mean:
List<List<string>> List2D = new List<List<string>>();
for (int i = 0; i < 5; i++)
{
List2D[2].Add("i")
}
I get the following error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
EDIT: Any idea how to fill in a 4D list?
List<List<List<List<string>>>> List4D = new List<List<List<List<string>>>>();
for (int i = 0; i < List1.Count; i++)
{
List<List<List<string>>> List3D = new List<List<List<string>>>();
for (int j = 0; j < List2.Count; j++)
{
List<List<string>> List2D = new List<List<string>>();
for (int k = 0; k < List3.Count; k++)
{
List<string> Lijst1D = new List<string>();
List2D.Add(Lijst1D);
}
List3D.Add(List2D);
}
List4D.Add(List3D);
}
So later I can call: List4D[2][3][0].Add("test");
Since you just created your List2D and not added any nested list into it, you can't access its third element (there is nothing there).
You have to add some items first:
List<List<string>> List2D = new List<List<string>>();
List2D.Add(new List<string>());
List2D.Add(new List<string>());
List2D.Add(new List<string>());
for (int i=0; i<5; i++)
{
List2D[2].Add("i")
}
Update
Well, core idea of filling that list remains the same: if you want to access List4D[2][3][0] - first you need to fill all of lists in "path".
You can do it something like this:
List<List<List<List<string>>>> List4D = new List<List<List<List<string>>>>();
int i1 = 2, i2 = 3, i3 = 0;
for (int i = 0; i <= Math.Max(i1, 1); i++)
List4D.Add(new List<List<List<string>>>());
for (int i = 0; i <= Math.Max(i2, 1); i++)
List4D[i1].Add(new List<List<string>>());
for (int i = 0; i <= Math.Max(i3, 1); i++)
List4D[i1][i2].Add(new List<string>());
List4D[i1][i2][i3].Add("test");
Frankly, idea of 4D list looks a little bit "syntetic". In real application probably it is not the best data structure because of clumsy addressing.

How to code for dynamic for-loop levels?

My problem is like this:
I have several lists need to be permuted, but the list numbers are unknowable. And every element numbers in every list are also unknowable. Sicne I would like to traverse all list element combination, like 1) pick A from list 1, A from list 2, A from list 3; 2) ick A from list 1, A from list 2, B from list 3 ... for ALL permutation.
I use nested for-loop to traverse, like if I have two lists, then:
for (int i = 0; i < list[0].EnergyParameters.ListEnergyLevelCandidates.Count; i++)
{
for (int j = 0; j < list[1].EnergyParameters.ListEnergyLevelCandidates.Count; j++)
{
// Do sth
}
}
If I have three lists, then:
for (int i = 0; i < list[0].EnergyParameters.ListEnergyLevelCandidates.Count; i++)
{
for (int j = 0; j < list[1].EnergyParameters.ListEnergyLevelCandidates.Count; j++)
{
for (int k = 0; k < list[2].EnergyParameters.ListEnergyLevelCandidates.Count; k++)
{
// Do sth
}
}
}
Because the list numbers are unknowable, so the nest numbers are unknowable, which means, I don't know how many levels of for-loop needs to be written.
Under this kind of circumstance, how can I write code for dynamic for-loop levels? I don't want to write 10 loops for 10 lists.
In case you do not know how many lists there are, you do not write nested loops: instead, you write recursion. At each level of the invocation you loop a single list, like this:
void AllCombos(List<string>[] lists, int level, string[] current) {
if (level == lists.Length) {
// Do somthing; items of current[] contain elements of the combination
} else {
foreach (var s in lists[level]) {
current[level] = s;
AllCombos(lists, level+1, current);
}
}
}
Call AllCombos as follows:
var lists = new List<string>[10];
for (int i = 0 ; i != 10 ; i++) {
lists[i] = PopulateMyList(i);
}
string[] current = new string[lists.Length];
AllCombos(lists, 0, current);

Categories