Is it possible to concreate variable in c# [duplicate] - c#

This question already has answers here:
C# dynamically set property [duplicate]
(5 answers)
Closed 1 year ago.
I have some variables and there results which are going into database.
For example
float[] qty1;
Quote quote = new Quote();
quote.qty1 = qty1[0];
quote.qty2 = qty1[1];
quote.qty3 = qty1[2];
quote.qty4 = qty1[3];
I try to make this process more dynamic
for (int i = 0; i <= 3; i++)
{
quote.qtyi = qty1[i];
}
please help me how i can use quote.qtyi and value of i, so it will read quote.qty1, quote.qty2, quote.qty3, quote.qty4

Use reflection:
for (int i = 0; i <= 3; i++)
{
quote.GetType().GetProperty("qty"+i).SetValue(quote,qt1[i]);
}
quote.getType().getProperty("qty"+i) -> Gets the property called "qty"+i from the object "quote".
.setValue(quote,qt1[i]) -> sets the value "qt1[i]" to the property (if she exists) of the object "quote".
My first answer had TYPOS, now it's compilable

Related

Iterating through variable names with for loop [duplicate]

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).

How to solve argument out of range exceptions [duplicate]

This question already has answers here:
ArgumentOutOfRangeException on initialized List
(1 answer)
How to initialize a List<T> to a given size (as opposed to capacity)?
(16 answers)
Closed 4 years ago.
So I've been looking around for quite a while to try and find a solution to this.
I've been trying to make a card game and am stuck at a section in which I create a cad along with its properties. i decided to make it in the form of an array. The code looks like:
(not sure what happened with these first ones)
string[] dogs = System.IO.File.ReadAllLines(#"C:\Users\corin\Documents\C# coding\dogs.txt");
int individual = totalCards / 2;
Random r = new Random();
int Cards = totalCards / 2;
List<List<int>> playerCards = new List<List<int>>(Cards);
for (int x = 0; x < (Cards-2); x++)
{
playerCards[0].Add(Int32.Parse(dogs[x]));//Cards
playerCards[1].Add(r.Next(1, 6));//Drool
playerCards[2].Add(r.Next(1, 101));//Exercise
playerCards[3].Add(r.Next(1, 11));//Intelligence
playerCards[4].Add(r.Next(1, 11));//Friendliness
}
No errors are raised before I run the code but when I try it an Argument out of range exception occurs for the line: playerCards[0].Add(Int32.Parse(dogs[x]));
I tried removing it and the same error occured for the next line. I'm not sure what I've done wrong and have tried to find a solution for quite some time. If anyone has any tips or answers that would be great.
Thanks
try this :
string[] dogs = System.IO.File.ReadAllLines(#"C:\Users\corin\Documents\C# coding\dogs.txt");
int individual = totalCards / 2;
Random r = new Random();
int Cards = totalCards / 2;
List<List<int>> playerCards = new List<List<int>>();
//the missing piece
for (int i = 0; i < (Cards ); i++)
{
playerCards.add(new List<int>());
}
for (int x = 0; x < (Cards-2); x++)
{
playerCards[0].Add(Int32.Parse(dogs[x]));//Cards
playerCards[1].Add(r.Next(1, 6));//Drool
playerCards[2].Add(r.Next(1, 101));//Exercise
playerCards[3].Add(r.Next(1, 11));//Intelligence
playerCards[4].Add(r.Next(1, 11));//Friendliness
}
In addition to the previous answers: new List<List<int>>(Cards) doesn't do what you think it does. It sets capacity, not elementCount (or whatever it's called). When bounds are checked, elementCount is used, not capacity. capacity is useful when you have a good idea how many elements you have, to avoid reallocations and don't waste space.
So yes, before accessing by index you should add elements into the list manually.

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--)
// ...

Looping through a list is throwing an Out of boundaries exception C# [duplicate]

This question already has answers here:
List<> Capacity returns more items than added
(5 answers)
Closed 7 years ago.
Would anybody help me to understand what is wrong with this for loop why am I getting out of boundaries exception please?
Capacity of this particular list is set to 8.
public static List<Beds> BedsList = new List<Beds>(8);
private int GetFirstAvailableBed()
{
var result = 0;
for (int i = 0; i < Beds.BedsList.Capacity; i++)
{
if (Beds.BedsList[i] == null) // Here is trhowing the exception
{
result = i;
break;
}
}
return result;
}
Use List.Count instead of List.Capacity.
The Capacity property
Gets or sets the total number of elements the internal data structure can hold without resizing.
It's not the number of items in the list.
You should use List#Count
for (int i = 0; i < Beds.BedsList.Count; i++)

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