I want to assign value to elements of my array. after running this, all elements of ListResults are same as last element of ListROI.
ListResults = new DataPoint[nROIrow];
DataPoint TempRes = new DataPoint();
System.Collections.ArrayList List = new System.Collections.ArrayList();
for (int i = 0; i < nROIrow; i++)
{
TempRes.X = ListROI[i].X;
TempRes.Y = ListROI[i].Y;
TempRes.u = dispROIcorr[i, 0];
TempRes.v = dispROIcorr[i, 1];
ListResults[i] = TempRes;
disp.Xpix = ListResults[i].X;
disp.Ypix = ListResults[i].Y;
disp.X = ListResults[i].X;
disp.Y = ListResults[i].Y;
disp.U = ListResults[i].u;
disp.V = ListResults[i].v;
List.Add(disp);
bSAVE.Enabled = true;
}
You only create a new DataPoint(); one time. So you end up with an array full of references to that same single instance.
The simple fix:
ListResults = new DataPoint[nROIrow];
//DataPoint TempRes = new DataPoint();
System.Collections.ArrayList List = new System.Collections.ArrayList();
for (int i = 0; i < nROIrow; i++)
{
DataPoint TempRes = new DataPoint();
...
ListResults[i] = TempRes;
var disp = new ...
disp.Xpix = ListResults[i].X;
....
List.Add(disp);
}
The problem with your code is that you are reusing the TempRes variable. When you perform the "List.Add" you are just adding a reference to it, and all these references are (obviously) the same. You also modify it, so each identical reference logically points to the same identical data.
Instead, write:
System.Collections.ArrayList List = new System.Collections.ArrayList();
for (int i = 0; i < nROIrow; i++)
{
DataPoint TempRes = new DataPoint();
...
Note also that ArrayList is generally considered to be deprecated since .NET 2.0 and you should be using List<T> instead.
do
disp = new ... // whatever
before assigning values to disp[i].???
actually what is happening is all the references in your List are referring to disp which is the single object that was created outside the for loop, hence all items in List are pointing to same disp object, hence same values.
Related
I am trying to fill my DTO objects with for, but I got this error:
Index was out of range. Must be non-negative and less than the size of the collection
Here is my code:
public static List <BankDepositHistoryDTO> DtoTODomain()
{
MyketAdsEntities context = new MyketAdsEntities();
List<BankDepositHistoryDTO> bdto = new List<BankDepositHistoryDTO>();
//var transactionlist
var transactionlist = GetListoftransactions.GetAccountingListoftransactions();
for (int i = 0; i < transactionlist.Count; i++)
{
bdto[i].AccountId = transactionlist[i].AccountId;
bdto[i].Id = transactionlist[i].Id;
bdto[i].Amount = transactionlist[i].Amount;
bdto[i].AdditionalData = transactionlist[i].AdditionalData;
bdto[i].ClientIp = transactionlist[i].ClientIp;
bdto[i].Gateway = transactionlist[i].Gateway;
bdto[i].PaymentRefNumber = transactionlist[i].PaymentRefNumber;
bdto[i].ReturnUrl = transactionlist[i].ReturnUrl;
bdto[i].State = transactionlist[i].State;
bdto[i].Uuid = transactionlist[i].Uuid;
}
return bdto;
}
I got this message at here
bdto[i].AccountId = transactionlist[i].AccountId;
You've created an empty list, and aren't adding elements to it. You must first add an element, and then update its properties:
for (int i = 0; i < transactionlist.Count; i++)
{
BankDepositHistoryDTO b = new BankDepositHistoryDTO();
b.AccountId = transactionlist[i].AccountId;
b.Id = transactionlist[i].Id;b
b.Amount = transactionlist[i].Amount;
b.AdditionalData = transactionlist[i].AdditionalData;
b.ClientIp = transactionlist[i].ClientIp;
b.Gateway = transactionlist[i].Gateway;
b.PaymentRefNumber = transactionlist[i].PaymentRefNumber;
b.ReturnUrl = transactionlist[i].ReturnUrl;
b.State = transactionlist[i].State;
b.Uuid = transactionlist[i].Uuid;
bdto.Add(b);
}
Well obvously, bdto length is less than transactionlist length.
before your for loop you can resize bdto to match transactionlist
I totally agree with #Ashkan and #Mureinik's answer, but just to improve code you can use AutoMapper. It will reduce loop and iteration for every element. It seems that all the properties between these two objects is the same.
Mapper.CreateMap<Transaction,BankDepositHistoryDTO>();
BankDepositHistoryDTO obj = Mapper.Map<Transaction,BankDepositHistoryDTO>(TransactionObj);
Also if GetListoftransactions.GetAccountingListoftransactions(); returns List<BankDepositHistoryDTO>, you can directly return that object in method.
I have a for loop which invokes a method within it. I add the return of this method to a list however I am getting duplicates in the list (the last return from the method call is all the items in the list). Presumably this is because the result object is the same instance. Is there a way around this?
IList<CarResult> carResults = new List<CarResult>();
for (int i = 0; i < cars.Count(); i++)
{
result = calculation.RunForCar(
engineSize[i],
yearOfManufacture[i],
carResults.Add(result);
}
return carResults;
}
I'm going to make a qualified guess and try to explain what's going on, without knowing exactly what's happening in your RunForCar().
Presumably this is because the result object is the same instance.
Probably yes.
Here's an example. It will not create new instances of Foo, but re-use the same instance over and over. So every time the name changes it changes the name on the reference. The list itself only contains the references, and therefore all the items in the list will be changed if you change the name on the reference.
var list = new List<Foo>();
var result = new Foo();
for(int i = 0; i < 5; i++)
{
result.Name = i.ToString();
list.Add(result);
}
foreach (var foo in list)
{
Console.WriteLine(foo.Name);
}
Output:
4
4
4
4
4
If we instead do like the code below, we assign result to a new reference, and then we leave the existing references untouched.
var list = new List<Foo>();
var result = new Foo();
for(int i = 0; i < 5; i++)
{
result = new Foo()
{
Name = i.ToString()
};
result.Name = i.ToString();
list.Add(result);
}
foreach (var foo in list)
{
Console.WriteLine(foo.Name);
}
Output:
0
1
2
3
4
Is there a way around this?
Yes, you can simply create a new instance of result for every loop. Without knowing more about either CarResult or RunForCar I cannot say when it's best to create the new instance. But here's an example:
IList<CarResult> carResults = new List<CarResult>();
for (int i = 0; i < cars.Count(); i++)
{
result = new CarResult();
result = calculation.RunForCar(
engineSize[i],
yearOfManufacture[i]); // Fixed type-o?
carResults.Add(result);
}
return carResults;
Alternatively you can have a local variable inside the loop.
IList<CarResult> carResults = new List<CarResult>();
for (int i = 0; i < cars.Count(); i++)
{
var result = new CarResult(); // Will not be accessible outside of loop.
result = calculation.RunForCar(
engineSize[i],
yearOfManufacture[i]); // Fixed type-o?
carResults.Add(result);
}
return carResults;
If the result is the same instance, you need to replace IList with HashSet
You need to create a new instance or result object on every pass of the loop in order to avoid adding it by reference to carResults list. Oterwise, all items in carResults will hold the reference to the same object which will contain the data from the last loop cycle.
Below is my code,
List<float?> LValues = new List<float?>();
List<float?> IValues = new List<float?>();
List<float?> BValues = new List<float?>();
List<HMData>[] data = new List<HMData>[4];
List<HMData>[] Data = new List<HMData>[7];
float? Value_LfromList = 0;
float? Value_IfromList = 0;
float? Value_BfromList = 0;
int indexer=0;
foreach (var item in Read_xml_for_childobjects_id.Root.Descendants("object"))
{
data[indexer] = new List<HMData>(); // Error occuring on this line
for (int k = 0; k < 7; k++)
{
Value_LfromList = LValues.ElementAt(k);
Value_IfromList = IValues.ElementAt(k);
Value_BfromList = BValues.ElementAt(k);
Data[k].Add(new HMData { x = Value_LfromList, y = Value_IfromList, z = Value_BfromList });
}
indexer++;
}
As soon as I intend to add the element at Data list in following line,
Data[k].Add(new HMData { x = Value_LfromList, y = Value_IfromList, z = Value_BfromList });
I get an error as Object reference not set to instant of object,
I want output be as shown in following question link,
Result required as shown in this question,
I have tried by lots of ways but could not make it,will really appreciate help if provided,Thanks.
Your code is a nightmare. You should really think about refactoring...
You have to initialize the lists within Data array.
List<HMData>[] Data = new List<HMData>[7];
for(int i = 0; i < 7; i++)
Data[i] = new List<HMData>();
There are tons of other problems and questions that should be asked (like what's the difference between data and Data?, why are these array sized explicitly?). Without that knowledge every advice can be not enough to solve your real problem.
you just need to declare the list as
List<HMData> Data = new List<HMData>();
and add new element to the list by
Data.Add(new HMData { x = Value_LfromList, y = Value_IfromList, z = Value_BfromList });
I have a issue that i cant solve.
Here is the code
sik input = new sik();
for (int i = 0; i < 5; i ++)
{
input.skId = securitiesArray[i].skId;
input.country = securitiesArray[i].country;
}
sik[] inputs = new sik[]
{
input
};
Now i know this will only put 1 value in the sik[] list.
How can i put all the 5 values in this list.
Thanks
Note: i cannot initialize ski[] first. This has to be done in that order.
Any reason that it has to be an array?
List<sik> input = new List<sik>();
for (int i = 0; i < 5; i ++)
{
var newInput = new sik();
newInput.skId = securitiesArray[i].skId;
newInput.country = securitiesArray[i].country;
input.Add(newInput);
}
The reason that the List is useful is that it can dynamically grow with you, so you have no need to worry about how many instances you may need to add.
MSDN Documentation for List and all of it's glorious methods
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
sik[] inputs = new sik[5];
for (int i = 0; i < 5; i ++)
{
sik input = new sik();
input.skId = securitiesArray[i].skId;
input.country = securitiesArray[i].country;
inputs[i] = input;
}
You can use Linq to do this.
sik[] inputs = securitiesArray.Select(item =>
new sik()
{
skId = item.skId,
country = item.country
}).ToArray();
You can't have variable size array, instead you can use List.
List<sik> siks = new List<sik>();
sik input = new sik();
for (int i = 0; i < 5; i ++)
{
input.skId = securitiesArray[i].skId;
input.country = securitiesArray[i].country;
siks.Add(input);
}
If you want array yet, use sik[] inputs = skis.ToArray();
You can also do this,
List<sik> input=new List<sik>();
for(int i=0;i<securitiesArray.Length;i++)
{
input.Add(new{skId=securitiesArray[i].skid,country=securitiesArray[i].country});
}
For what it's worth, here the Linq approach:
sik[] inputs = Enumerable.Range(0, 5)
.Select(i => new sik{ kId = securitiesArray[i].skId, country = securitiesArray[i].country})
.ToArray();
If securitiesArray is of type sik(the properties suggest), you can select directly from it:
sik[] inputs = securitiesArray.Take(5).ToArray();
SubnetConvert SubnetOctet1 = new SubnetConvert();
SubnetConvert SubnetOctet2 = new SubnetConvert();
SubnetConvert SubnetOctet3 = new SubnetConvert();
SubnetConvert SubnetOctet4 = new SubnetConvert();
int Octet1 = int.Parse(txtOctet1.Text);
SubnetOctet1.OctetConvert = Octet1;
lblOctet1.Text = SubnetOctet1.SendBinary;
int Octet2 = int.Parse(txtOctet2.Text);
SubnetOctet2.OctetConvert = Octet2;
lblOctet2.Text = SubnetOctet1.SendBinary;
int Octet3 = int.Parse(txtOctet3.Text);
SubnetOctet3.OctetConvert = Octet3;
lblOctet3.Text = SubnetOctet1.SendBinary;
int Octet4 = int.Parse(txtOctet4.Text);
SubnetOctet4.OctetConvert = Octet4;
lblOctet4.Text = SubnetOctet1.SendBinary;
is it possible to put all this code in a For loop like
For (int i = 1; i <=4; i++)
{
SubnetConvert SubnetOctet[i] = new SubnetConvert();
int Octet[i] = int.Parse(txtOctet[i].Text);
SubnetOctet[i].OctetConvert = Octet[i];
lblOctet[i].Text = SubnetOctet[i].SendBinary;
}
I have tried the coding above and it doesn't work, I have just put it there for an example of what I want to achieve
The code sample is not something possible - there is no support for control arrays as you have shown.
A better way would be to write a function that encapsulates the repeating code and pass in the differing parameters.
private void SetBinaryValue(string value, Label display)
{
int Octet = int.Parse(value);
SubnetOctet.OctetConvert = Octet;
display.Text = SubnetOctet.SendBinary;
}
You would call this function like so:
SetBinaryValue(txtOctet1.Text, lblOctet1);
SetBinaryValue(txtOctet2.Text, lblOctet2);
Note that you only need one SubnetConvert with this approach (which you can either initialize within the function, or as a field).
It's perfectly possible to loop through named controls using FindControl:
var subnetOctet = new SubnetConvert();
for (int i = 1; i <= 4; ++i) {
// ID suffix as string
var indexText = i.ToString(CultureInfo.InvariantCulture);
// ID of TextBox and Label
var textBoxId = "txtOctet" + indexText;
var labelId = "lblOctet" + indexText;
// The TextBox and the Label
var textBox = (TextBox)FindControl(textBoxId);
var label = (Label)FindControl(labelId);
// Parse the value into an int
int octet = int.Parse(textBox.Text);
subnetOctet.OctetConvert = octet;
// Update the TextBox's Test
label.Text = subnetOctet.SendBinary;
}
One advantage to using this method is that you can add more controls on the fly, or even programmatically, and if you keep track of the number of subnets you need to handle, you do not have to update your code.
You could also create an Array with the your objects as the elements and then loop through the array and execute the functions based on the array position at loop position;
Dog pet1 = new Dog();
Dog pet2 = new Dog();
Dog pet3 = new Dog();
Dog pet4 = new Dog();
//create a list of pets and add your pets to them
List<Dog> pets = new List<Dog>();
pets.Add(pet1);
pets.Add(pet2);
pets.Add(pet3);
pets.Add(pet4);
//Using a for each loop to go through each element in the array and execute identical actions on each
//element
foreach (Dog pet in pets)
{
pet.SetName("Fido");
}
//or create a for each loop that will allow you to know the position
//you are currenly at in the arry as the integer of i increments in the loop
for (int i = 0; i <= pets.Count; i++)
{
pets[i].SetName("Fido");
}
Ideally what you will want to do is create a single object and insert multiple instances of the object into the list via another loop and then use the foreach or the for loop to access an element of the list to manipulate a singular instance.
Dog dog = new Dog();
//create a list of pets and add your pets to them
List<Dog> pets = new List<Dog>();
for (int i = 0; i <= 5; i++)
{
pets.Add(dog);
}
//Using a for each loop to go through each element in the array and execute identical actions on each
//element
foreach (Dog pet in pets)
{
pet.SetName("Fido");
}