Iterating through variable names with for loop [duplicate] - c#

This question already has answers here:
Variables in a loop
(9 answers)
Loop through object variables with different number on the name [duplicate]
(5 answers)
Iteration with variable name [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to use a for loop to iterate through a series of variable names each ending in a number from 1 to 10. I have seen a few other answers to this question but have been unable to make any work for my specific situation. My code is as follows:
string cat2Pos0 = cat2[0];
int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
List<int> indexOfPos0 = new List<int>();
bool check = cat2.Contains(cat2Pos0);
int index = 0;
if (check == true)
{
for (int i = 0; i < numOfPos0; i++)
{
index = cat2.FindIndex(x => x == cat2Pos0);
indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
}
}
else if (cat2Pos0 == "-")
{
numOfPos0 = 17;
}
I need to loop through 10 variables names cat1 - cat10. In the code: whenever there is the phrase "cat" I need to be able to adjust it depending on a for loop e.g. cat1 or cat5:
string cat3pos0 = cat3[0];
or:
index = cat3.FindIndex(x => x == cat3Pos0);
Unfortuantely, I am unable to simply write out each variation individually as that would use up almost 3700 lines of code and I was hoping that there would be a better way of achieveing this.
Many thanks, all help is greatly appreciated,
Josh

See here how to use reflection for this. (something like this.GetType().GetField("cat" + i.ToString());.)
But I would really suggest changing your variables to one array of 10 variables. So cat will be an array of arrays (since your cat's seem to be arrays).

Related

Random Number Generator with no repeats [duplicate]

This question already has answers here:
Random number generator with no duplicates
(12 answers)
Generating random numbers without repeating.C# [duplicate]
(11 answers)
Closed 1 year ago.
I am trying to work out how to make a random number generator that outputs 4 integers going from 0 to 9 without any repeats.
Would like some help please
i have just started coding in c# but cant find any answers to my issue
You need to remove the int from the checking if it has already repeated.
so:
if (val1 == val2)
{
val2 = rnd.Next(1,11);
}
and not:
if (val1 == val2)
{
int val2 = rnd.Next(1,11);
}
The latter will declare a new variable "val2" which exists only inside the scope of the "if" block, instead of updating the existing "val2" variable as you intended. This is called "shadowing".
For "quick and dirty" solution you can use LINQ. For example something like this will randomly select 4 numbers in range from 0 to 9:
var random = new Random();
var numbers = Enumerable.Range(0, 10)
.OrderBy(_ => random.Next())
.Take(4)
.ToList();
In case you need something more prescise and faster then you can implement Fisher–Yates shuffle for example.

C# - Field values of an array picking up values of a loop [duplicate]

This question already has answers here:
How to get first N elements of a list in C#?
(7 answers)
How do I clone a range of array elements to a new array?
(26 answers)
Closed 5 years ago.
I'm training C# on a simple card game. I have methods that shuffle and deals the cards. I have a random deck that is well generated.
Is it possible to set an array for the player1 cards, picking up the first ten values of the array.
Here is a part of my code :
currentCard = 0;
public Card DealCard()
{
if (currentCard < deck.Length)
return deck[currentCard++];
else
return null;
}
I want to pick up for example ten first values of
deck[currentCard++]
Any suggestions will be appreciated, thanks for your help !
You mean you want to pull the first 10 enties into another array? Something like;
var player1Cards = deck.Take(10);
or
List<int> player1Cards = new List<int>();
for (int i = 0; i < 10; i++){
player1Cards.Add(deck[i]);
}

for-loop to foreach with negative(i--) statement [duplicate]

This question already has answers here:
Possible to iterate backwards through a foreach?
(13 answers)
Closed 7 years ago.
If I have list of data, I want delete separate rows (not bulk delete) with a loop.
Here my Code
var objecctCount = listItemsDelete.Count;
for (int i = objecctCount; i > 0; i--)
{
listItemsDelete[i].DeleteObject();
spDataContext.ExecuteQuery();
}
where,
listItemsDelete is list of data,
listItemsDelete[i].DeleteObject(); delete separate row from listItemsDelete,
spDataContext.ExecuteQuery(); is helps update values to the listItemsDelete
My logic is working good.
my question is, Is it possible to change the for-loop to foreach with negative statement? Because my knowledge about foreach is helps to work with positive statement(I++).
So you want to reverse the loop?
foreach(var obj in listItemsDelete.Reverse())
{
obj.DeleteObject();
spDataContext.ExecuteQuery();
}
Since you are using .NET 2 you can't use LINQ. Stay with your for-loop but fix following error.
Instead of
for (int i = objecctCount; i > 0; i--)
// ...
use this:
for (int i = objecctCount - 1; i >= 0; i--)
// ...

How to Create a Dynamic Array? [duplicate]

This question already has answers here:
Dynamic array in C#
(9 answers)
Closed 7 years ago.
static void Main(string[] args)
{
int numberOfTheWords = 1;
string[] words = new string[numberOfTheWords];
Console.WriteLine("You can exit from program by writing EXIT ");
Console.WriteLine("Enter the word: ");
for(int i = 0; i < numberOfTheWords; i++)
{
words[i] = Console.ReadLine();
if (words[i] == "EXIT")
break;
else
numberOfTheWords++;
}
}
Guys I am trying to expand the lengt of the array but "numberOfTheWords" variable is in the "for loop' scope" so it does not effect the global "numberOfTheWord" variable and i cannot expand the array length. What I am trying to achieve is to make dynamic array. I do not want to declare the length of the array. When the user input a word, the length of the array will be increased automatically. Can you help me about how to do this?
This can be easily done with a List.
Example:
List<string> words = new List<string>();
...
words.Add(Console.ReadLine());
Lists are dynamically expanding and you don't have to manage the size of the list on your own. The .NET Framework does that for you. You can also insert an item anywhere in the middle or delete one from any index.
You just need to use List:
var words = new List<string>();
An array does not dynamically resize. A List does. With it, we do not need to manage the size on our own. This type is ideal for linear collections not accessed by keys.

Filling an array of int at declaration [duplicate]

This question already has answers here:
Direct array initialization with a constant value
(6 answers)
Fastest way to fill an array with a single value [duplicate]
(3 answers)
Closed 8 years ago.
I'd like to declare an array of int rows with a variable size (X) and init all values to 1. For the moment I use this :
int[] rows = new int[X];
for (int i = 0; i < rows.Length; i++)
{
rows[i] = 1;
}
Is there any faster/shorter way to do it with some sort of fill(1) or int[] rows = new int[X] {1}; ?
LINQ:
int[] rows = Enumerable.Repeat(element:1, count: X).ToArray();// named parameter - X
// doesn't tell anything

Categories

Resources