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();
Related
Variable.cs
public string[] CcEmails { get; set; }
Mail.cs
EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');
here i got two strings eg. xxxx#gmail.com ; yyy#gmail.com
MailProcess.cs
dataRPT1=get data from sql
EDTO.CcEmails = new string[dataRPT1.Rows.Count];
for (int i = 0; i < dataRPT1.Rows.Count; i++)
{
EDTO.CcEmails[i] = dataRPT1.Rows[i]["email_addr"].ToString();
}
Here i got list of string eg.aaa#gmail.com ......
I am try to add with existing but it add only new values..Anyone could help me..
I tend to use union, although that will remove duplicate entries. But to keep all entries you can use Concat on the array.
var emailString = "me#test.com;you#test.com";
string[] emails = emailString.Split(';');
string[] emailsFromSQL = new string[3];
emailsFromSQL[0] = "everyone#test.com";
emailsFromSQL[1] = "everyone2#test.com";
emailsFromSQL[2] = "everyone2#test.com";
//No Duplicates
var combined = emails.Union(emailsFromSQL).ToArray();
//Duplicates
var allCombined = emails.Concat(emailsFromSQL).ToArray();
Thanks
I find the easiest way of doing this is to create a list, add items to the list, then use string.Join to create the new string.
var items = new List<string>();
for (int i = 0; i < dataRPT1.Rows.Count; i++)
{
items.Add(dataRPT1.Rows[i]["email_addr"].ToString());
}
EDTO.CcEmails = string.Join(";", items);
Update after changed question:
If the type of the CcEmails is an array, the last line could be:
EDTO.CcEmails = items.ToArray();
I am getting "index out of range" from this loop. But I need to use new elements that loop founds, how do I do that? Please help to fix the problem
int linkCount = driver.FindElements(By.CssSelector("a[href]")).Count;
string[] links = new string[linkCount];
for (int i = 0; i < linkCount; i++)
{
List<IWebElement> linksToClick = driver.FindElements(By.CssSelector("a[href]")).ToList();
links[i] = linksToClick[i].GetAttribute("href");
}
I think that you could refactor your code:
var linkElements = driver.FindElements(By.CssSelector("a[href]")).ToList();
var links = new List<string>();
foreach (var elem in linkElements)
{
links.Add(elem.GetAttribute("href"));
}
If that works, you could simplify the query:
var instantLinks = driver.FindElements(By.CssSelector("a[href]"))
.Select(e => e.GetAttribute("href"))
.ToList();
You can rewrite your code to bypass the for loop:
string[] links = driver.FindElements(By.CssSelector("a[href]")).Select(l => l.GetAttribute("href")).ToArray();
This should also avoid the index out of range problem, and cut down the amount of code you have to write.
First of all i dont see a point in assigning linkstoclick values inside loop... And Reason for error must be that linksToClick list's length is more than that of linkCount.
int linkCount = driver.FindElements(By.CssSelector("a[href]")).Count;
List<string> links = new List<string>();
for (int i = 0; i < linkCount; i++)
{
List<IWebElement> linksToClick = driver.FindElements(By.CssSelector("a[href]")).ToList();
if (linksToClick.Count < i)
links.Add(linksToClick[i].GetAttribute("href"));
}
This might help with the out of range exception.
Doing this allows you to create a list of type: string without having to explicitly define the size of the list
the first one gets all of your elements by tag name ...let's assume 5.
in the loop, your driver get's all the elements by css selector, and you might have a different number here. let's say 4.
then, you might be trying to set the fifth element in a four element array.
boom.
Easiest fix to debug:
int linkCount = driver.FindElements(By.TagName("a")).Count;
string[] links = new string[linkCount];
// WRITE OUT HOM MANY links you have
for (int i = 0; i < linkCount; i++)
{
List<IWebElement> linksToClick = driver.FindElements(By.CssSelector("a[href]")).ToList();
// ASSERT THAT YOU HAVE THE SAME AMOUNT HERE
If (links.Count != linksToClick.Count)
// your logic here
links[i] = linksToClick[i].GetAttribute("href");
}
i am trying to add a location name to my output text files.
As you can see my numbers are incrementing properly. But i have coded like after number 45 i need to reset the number to 1, also the Carousel:45 should change to ** Carousel1:1**. But it is not happening... why it is not happening. any help please!!!!
My code snippet:
public void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string CarouselName = enter.Text;
int[] cols = new int[] { 15, 15, 25, 15, 15 };
StringBuilder sb = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
sb.Append(cells[c].Replace(" ", "_").PadRight(cols[c]));
sb.AppendLine("Location".PadRight(15));
sb.AppendLine();
int tmpCarousel = 0;
int carouselNumber = 0;
Dictionary<string, int> namesForCarousels = new Dictionary<string, int>();
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
sb.Append(textfile[i].Cells[c].Replace(" ", "_").PadRight(cols[c]));
string name = textfile[i].Cells[1];
if (namesForCarousels.TryGetValue(name, out tmpCarousel) == false)
{
carouselNumber++;
if (carouselNumber > 45)
carouselNumber = 1;//resetting to number1, but name is
//not changing to Carousel1..
namesForCarousels[name] = carouselNumber;
}
var strCorousel = lstMX.Find(x => x.MAX_PN.Equals(name)).Carousel;
strCorousel = (String.IsNullOrEmpty(strCorousel)) ? CarouselName : strCorousel;
sb.Append(String.Format("{0}:{1}", strCorousel, carouselNumber).PadRight(15));
sb.Append("\r\n");
}
System.IO.File.WriteAllText(#"Z:\Desktop\output.TXT", sb.ToString());
}
OUTPUT i need
I need after Carousel:45 >>> i need Carousel1:1. How can i do this..?
You never use the numbers stored in your dictionary namesForCarousels after setting them. Probably you want
sb.Append(String.Format("{0}:{1}", strCorousel, namesForCarousels[name]).PadRight(15));
Also, you should rename carouselNumber to something like carouselNumberCounter. It's not the number of the current carousel, it's a counter used to assign a number to the next carousel. And for additional clarity, get rid of the local variable tmpCarousel and do:
if (!namesForCarousels.ContainsKey(name))
{
You might find it easier to follow your code if you use more descriptive variable names. It's not entirely clear what you're trying to do, but I assume you want to re-use the same carousel number for a given "Max Pn" if you've already allocated it - at the moment, you populate that mapping but you don't use it, you are reliant on max pn being in order. I don't actually see why carousel number wouldn't reset, but if you tidy it up perhaps you have a better chance of seeing what is happening.
Also given your null reference exception from your other question, this protects against that - though it probably indicates another problem elsewhere in the population of your "lstMx".
public static void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string defaultCarouselName = enter.Text;
int[] columnPaddings = new int[] { 15, 15, 25, 15, 15 };
StringBuilder completedOutputBuilder = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
completedOutputBuilder.Append(cells[c].Replace(" ", "_").PadRight(columnPaddings[c]));
completedOutputBuilder.AppendLine("Location".PadRight(15));
completedOutputBuilder.AppendLine();
int carouselNumberForEntry = 0;
Dictionary<string, int> maxPnToCarouselNumber = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
completedOutputBuilder.Append(_textfile[i].Cells[c].Replace(" ", "_").PadRight(columnPaddings[c]));
string maxPnForEntry = textfile[i].Cells[1];
int previouslyAllocatedCarouselNumberForMaxPn = 0;
if (maxPnToCarouselNumber.TryGetValue(maxPnForEntry, out previouslyAllocatedCarouselNumberForMaxPn) == false)
{
// assign a new courousel number for this max pn
carouselNumberForEntry++;
if (carouselNumberForEntry > 45)
carouselNumberForEntry = 1;
// for better clarity use add
maxPnToCarouselNumber.Add(maxPnForEntry, carouselNumberForEntry);
}
else
{
// use the carousel number previous assigned for this maxPn
carouselNumberForEntry = previouslyAllocatedCarouselNumberForMaxPn;
}
// find the related max pn carousel entry (if relatedPn is not found this suggests a problem elsewhere)
MAX_PN_Carousel relatedPn = lstMx.Find(x => x.MAX_PN != null && x.MAX_PN.Equals(maxPnForEntry, StringComparison.OrdinalIgnoreCase));
// assign the name from the entry, or use the default carousel name if unavailable
string carouselNameForMaxPn = (relatedPn == null || String.IsNullOrWhiteSpace(relatedPn.Carousel)) ? defaultCarouselName : relatedPn.Carousel;
// add the new column in the output
completedOutputBuilder.Append(String.Format("{0}:{1}", carouselNameForMaxPn, carouselNumberForEntry).PadRight(15));
completedOutputBuilder.Append("\r\n");
}
System.IO.File.WriteAllText(#"c:\dev\output.TXT", completedOutputBuilder.ToString());
}
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 use a simple array: contentHouseOne[] that contains strings. But in the Do/While loop it isn't working! It seems like the code don't understand that it's a string when a new object is to be created!? It works when I hardcode the string like I show below. Help is preciated! Thanks!
This isn't working:
listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition));
But this works:
listHouseParts.Add(new HousePart(content, "100x100", newPosition));
EDIT:
Here are some code to declare arrays
string[] contentHouseOne = new string[] { "ruta100x100Red",
"ruta100x100Grey",
"ruta100x100Green",
"ruta100x100Yellow",
"ruta100x100Blue" };
bool[,] occupiedPositions = new bool[500,500];
Here are some code to set all grid positions to false
for (int i = 0; i < gridCol; i++)
for (int ii = 0; ii < gridRow; ii++)
occupiedPositions[i, ii] = false;
And finally here are the code that I have the problem
int i = 0;
do
{
Vector2 newPosition = NewRandomPosition;
if (occupiedPositions[(int)newPosition.X, (int)newPosition.Y] == false)
{
listHouseParts.Add(new HousePart(content,
contentHouseOne[i], newPosition));
occupiedPositions[(int)newPosition.X, (int)newPosition.Y] = true;
i++;
}
}
while (i <= 5);
Your string array includes five elements:
string[] contentHouseOne = new string[] { "ruta100x100Red",
"ruta100x100Grey",
"ruta100x100Green",
"ruta100x100Yellow",
"ruta100x100Blue" };
But your while loop ends if your running variable i is greater than 5
while (i <= 5);
which causes a IndexOutOfBounds exception on contentHouseOne, because the 6th element at index 5 isn't defined.
You should change your while condition to (i < 5).
Try this so atleast you know if its empty or not
HousePart housePart = new HousePart();
housePart.Content = content;
if (!string.IsNullOrEmpty(contentHouseOne[i]))
housePart.ContentHouseOne = contentHouseOne[i];
else
housePart.ContentHouseOne = string.Empty;
housePart.NewPosition = newPosition;
listHouseParts.Add(housePart);