How to add item to array in C# - c#

I have a loop that is generating about 150 unique strings. How can I add these strings to an array?
Here is my loop:
for (int intCounter = 0; intCounter < projectCount; intCounter ++)
{
var projectname = project.value[intCounter].name;
var releaseUri = "http://tfs1:8080/tfs/defaultcollection/" + projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + date + "T00:00:00.00Z";
Console.WriteLine(releaseUri);
}
The Console.WriteLine(releaseUri) prints each url. but I would like to store the releaseUri in an array.

Lists are normally better than arrays.
var releaseUris = new List<string>();
foreach(var project in projects)
{
var releaseUri = $"http://tfs1:8080/tfs/defaultcollection/" + project.projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + project.date + "T00:00:00.00Z";
releaseUris.Add(releaseUri);
}

#ShaneP,
You will need to declare an array outside of the for loop like so.
string[] releaseUriArray = new string[projectCount];
for (int intCounter = 0; intCounter < projectCount; intCounter ++)
{
var projectname = project.value[intCounter].name;
var releaseUri = "http://tfs1:8080/tfs/defaultcollection/" + projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + date + "T00:00:00.00Z";
// Here you are adding the releaseUri strings to the releaseUriArray
releaseUriArray[intCounter] = releaseUri;
}
// print your uris from the array here
for (int intCounter = 0; intCounter < projectCount; intCounter ++)
{
var releaseUri = releaseUriArray[intCounter];
Console.WriteLine(releaseUri);
}

You can use an array in this case as you know the number of elements. Initialize it and set the items as you go
var arr = new string[projectCount];
for (int intCounter = 0; intCounter < projectCount; intCounter ++)
{
var projectname = project.value[intCounter].name;
var releaseUri = "http://tfs1:8080/tfs/defaultcollection/" + projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + date + "T00:00:00.00Z";
Console.WriteLine(releaseUri);
arr[intCounter] = releaseUri;
}

If you now projectCount then you can create an array with needed element numbers and just set its items by index.
var urls = new string[projectCount];
for (int intCounter = 0; intCounter < projectCount; intCounter ++)
{
var projectname = project.value[intCounter].name;
var releaseUri = "http://tfs1:8080/tfs/defaultcollection/" + projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + date + "T00:00:00.00Z";
urls[i] = releaseUri;
}
Or you can just use an dynamic array and add elements using Add() method to be able to change array size after initialization.
var urls = new List<string>();
for (int intCounter = 0; intCounter < projectCount; intCounter ++)
{
var projectname = project.value[intCounter].name;
var releaseUri = "http://tfs1:8080/tfs/defaultcollection/" + projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + date + "T00:00:00.00Z";
urls.Add(releaseUri);
}
Also you no need to use loops and can solve your problem with just 1 string of code using LINQ:
var urls = project
.value
.Select(p => "http://tfs1:8080/tfs/defaultcollection/" + p.projectname + "/_apis/release/releases?api-version=3.0-preview.2&searchText=911&minCreatedTime=" + date + "T00:00:00.00Z")
.ToArray();

One easy way to do this would be to create a template Uri that has placeholders for project name and date (using {0} and {1} in the string), then with some Linq extension methods (Select and ToList) and string.Format, you can and generate your strings from an Enumerable.Range:
// Project name and date will be inserted where {0} and {1} are below
string uriTemplate = "http://tfs1:8080/tfs/defaultcollection/{0}/_apis/release/" +
"releases?api-version=3.0-preview.2&searchText=911&minCreatedTime={1}T00:00:00.00Z";
string[] releaseUris = Enumerable.Range(0, projectCount)
.Select(i => string.Format(uriTemplate, project.value[i], date))
.ToArray();

Related

Print a List of ints as a matrix

I have a List of 9 integers and I want to print all elements from the list as a matrix 3,3. And I have to avoid unnecessary white space on the end of every line.
Is it possible to use String.Join ?
Thanks.
Here's my code:
int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[][] matrix = new int[input[0]][];
for (int i = 0; i < input[0]; i++)
{
int[] line = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
matrix[i] = line;
}
List<int> arr = new List<int>(9);
List<int> arr1 = new List<int>(9);
arr = Enumerable.Repeat(0, 9).ToList();
//for (int i = 0; i < 9 ; i++) sum[i%3, i/3] = 0;
for (int row = 0; row < input[0] - 2; row++)
{
for (int col = 0; col < input[1] - 2; col++)
{
arr1.Add(matrix[row][col]);
arr1.Add(matrix[row][col + 1]);
arr1.Add(matrix[row][col + 2]);
arr1.Add(matrix[row + 1][col]);
arr1.Add(matrix[row + 1][col + 1]);
arr1.Add(matrix[row + 1][col + 2]);
arr1.Add(matrix[row + 2][col]);
arr1.Add(matrix[row + 2][col + 1]);
arr1.Add(matrix[row + 2][col + 2]);
if (arr1.Sum() > arr.Sum())
{
arr = arr1.Select(a => a).ToList();
}
arr1.Clear();
}
}
Console.WriteLine($"Sum = {arr.Sum()} ");
// print the list as a matrix
This is how I would print it using String.Join:
List<int> asd = new List<int> {1,2,3,4,5,6,7,8,9};
for (int i = 0; i < asd.Count; i +=3)
{
Console.WriteLine(string.Join(" ",asd.Skip(i).Take(3)));
}
Explanation: Walk in steps of 3. Skip the amount of numbers equal to the stepsize and take 3 to combine a row of the matrix.
You should reconsider the accepted answer because the performance is poorly with many items.
It may be irrelevant for your current count of items but still hear my warning.
I ran the following code snippet:
var sb = new StringBuilder();
for (int i = 0; i < asd.Count; i +=3)
sb.AppendLine(string.Join(" ", asd.Skip(i).Take(3)));
Console.WriteLine(sb.ToString());
used a StringBuilder to remove the time relevant Console.WriteLine(); for every item in the loop.
This approach takes 756,115ms to complete, with 1,000,000 items.
Created the asd list like this:
var asd = Enumerable.Range(0, 1000000).ToList();
Every other answer given so far will perform way better.
The reason why the accepted solution performs this poorly is because of the .Skip() that is getting called inside the loop, it doesn't actually skip and go directly to this Position instead it again and again loops the list till it reaches this point.
My solution would be:
Console.WriteLine(string.Concat(asd.Select((x, i) => (i + 1) % 3 != 0 ? x + " " : x + Environment.NewLine)));
Which executes the same task in 8,610ms
For completness:
Wojtek's solution takes: 7,932ms
Nirmal Subedi' solution takes: 8,088ms
Note:
Changed it so that it uses a StringBuilder to build the string and only output the string once to the console, instead of calling Console.WriteLine() in a loop
Here my complete test routine:
var asd = Enumerable.Range(0, 1000000).ToList();
var sw1 = new Stopwatch();
sw1.Start();
Console.WriteLine(string.Concat(asd.Select((x, i) => (i + 1) % 3 != 0 ? x + " " : x + Environment.NewLine)));
sw1.Stop();
var sw2 = new Stopwatch();
sw2.Start();
var sb1 = new StringBuilder();
for (int i = 0; i < asd.Count; i += 3)
sb1.AppendLine(string.Join(" ", asd.Skip(i).Take(3)));
Console.WriteLine(sb1.ToString());
sw2.Stop();
var sw3 = new Stopwatch();
sw3.Start();
var sb2 = new StringBuilder();
int counter = 0;
string output = "";
foreach (int value in asd)
{
counter++;
if (counter % 3 == 0)
{
output += value;
sb2.AppendLine(output);
output = string.Empty;
}
else
output += value + " ";
}
Console.WriteLine(sb2.ToString());
sw3.Stop();
var sw4 = new Stopwatch();
sw4.Start();
var sb3 = new StringBuilder();
for (int i = 0; i <asd.Count / 3; i++)
{
int index = i * 3;
sb3.AppendFormat("{0} {1} {2}", asd[index], asd[index + 1], asd[index + 2]);
sb3.AppendLine();
}
Console.WriteLine(sb3.ToString());
sw4.Stop();
Console.WriteLine("MySolution: " + sw1.ElapsedMilliseconds);
Console.WriteLine("Mong Zhu's Solution: " + sw2.ElapsedMilliseconds);
Console.WriteLine("Wojtek's Solution: " + sw3.ElapsedMilliseconds);
Console.WriteLine("Nirmal Subedi's Solution: " + sw4.ElapsedMilliseconds);
Console.ReadKey();
Now You have your code pasted. Anyway, I created the sample to print the 3x3 matrix.
class Program
{
static void Main(string[] args)
{
StringBuilder stringBuilder = new StringBuilder();
List<int> numbers = new List<int>() {1,2,3,4,5,6,7,8,9 };
for (int i = 0; i <3; i++)
{
int index = i * 3;
stringBuilder.AppendFormat("{0}{1}{2}", numbers[index], numbers[index + 1], numbers[index + 2]);
stringBuilder.AppendLine();
}
Console.Write(stringBuilder.ToString());
Console.ReadLine();
}
}
Is that what you meant?
string output = string.Empty;
List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int counter = 0;
foreach (int value in myList)
{
output += value.ToString();
counter++;
if (counter % 3 == 0)
{
Console.WriteLine(output);
output = string.Empty;
}
}

Can I use a single for loop for two different declared objects?

public void SetupShip()
{
ship1 = new Ship("Olympic Countess");
ArrayList groupA = new ArrayList();
for (int i = 0; i < 10; i++)
{
groupA.Add(new room(5000, "A" + (i + 1)));
}
ArrayList groupB = new ArrayList();
for (int i = 0; i < 10; i++)
{
groupB.Add(new room(4000, "B" + (i + 1)));
}
}
Instead of using same conditions to loop different objects as done above, Can I add that new room within the same loop, as the looping condition is the same. Thanks.
I'd rather not use an obsolete ArrayList, but List<room>;
If you need to generate items, then generate them:
public void SetupShip() {
ship1 = new Ship("Olympic Countess");
List<room> groupA = Enumerable
.Range(1, 9)
.Select(i => new room(5000, "A" + i))
.ToList();
List<room> groupB = Enumerable
.Range(1, 9)
.Select(i => new room(4000, "B" + i))
.ToList();
}
P.S. Sure you can add two items in the same loop, i.e.
for (int i = 0; i < 10; i++) {
groupA.Add(new room(5000, "A" + (i + 1)));
groupB.Add(new room(4000, "B" + (i + 1)));
}
but I suggest not doing that but generating the list.
It will work
public void SetupShip()
{
ship1 = new Ship("Olympic Countess");
ArrayList groupA = new ArrayList();
ArrayList groupB = new ArrayList();
for (int i = 0; i < 10; i++)
{
groupA.Add(new room(5000, "A" + (i + 1)));
groupB.Add(new room(4000, "B" + (i + 1)));
}
}

c# acces array outside for loop

i was wondering how to acces a array outside a forloop.
string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");
for (int i = 0; i < 4; i++)
{
string[] linesSplitted = lines[i].Split(':');
}
TextboxName.Text = linesSplitted[0];
TextboxAddress.Text = linesSplitted[1];
TextboxZip.Text = linesSplitted[2];
TextboxTel.Text = linesSplitted[3];
TextboxEmail.Text = linesSplitted[4];
at this point, it does not recognize linesSplitted.
From your comment on another answer, I guess you want this:
string[] linesSplitted = new string[5];
for (int i = 0; i < 5; i++)
{
linesSplitted[i] = lines[i].Split(':')[1];
}
If this is not what you want, give us an example of the contents of the text file.
Declare the array outside of the loop. E.g.
string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");
string[] linesSplitted;
for (int i = 0; i < 4; i++)
{
linesSplitted = lines[i].Split(':');
}
TextboxName.Text = linesSplitted[0];
TextboxAddress.Text = linesSplitted[1];
TextboxZip.Text = linesSplitted[2];
TextboxTel.Text = linesSplitted[3];
TextboxEmail.Text = linesSplitted[4];
string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");
string[] linesSplitted;
for (int i = 0; i < 4; i++)
{
linesSplitted = lines[i].Split(':');
}
TextboxName.Text = linesSplitted[0];
TextboxAddress.Text = linesSplitted[1];
TextboxZip.Text = linesSplitted[2];
TextboxTel.Text = linesSplitted[3];
TextboxEmail.Text = linesSplitted[4];
I'm not to sure about what you're trying to achieve there...
string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");
List<string[]> data = new List<string[]>();
for (int i = 0; i < 4; i++)
{
data.Add(lines[i].Split(':'));
}
//Retrive array from list and value from array and set to text box
TextboxName.Text = linesSplitted[0];
TextboxAddress.Text = linesSplitted[1];
TextboxZip.Text = linesSplitted[2];
TextboxTel.Text = linesSplitted[3];
TextboxEmail.Text = linesSplitted[4];

How can i read string values from a table , and append to a single string

I am reading all the string values from a table and adding to an array as follows.
da2.Fill(ds, "DNAiusTwitter_Table");
int counts = ds.Tables[0].Rows.Count;
for (int i = 0; i < counts; i++)
{
names[i, 0] = ds.Tables[0].Rows[i][3].ToString();
}
How can I get string append = 'name1','name2','name3','name4'; How can I pass those values to this below code:
for (int i = 0; i < 1; i++)
{
HtmlGenericControl scriptTagLinks = new HtmlGenericControl("script");
scriptTagLinks.Attributes["type"] = "text/javascript";
string scrip1 = "$(function () {$(\"[src='" + names[i, 0] + "']\"" + ").pinit();});";
var scrip = "var tweetUsers=['" +append + "'," + "'" + splitted[3]+"']";
scriptTagLinks.InnerHtml = scrip;
this.Controls.Add(scriptTagLinks);
}
If you don't need the array later in code, I would use a StringBuilder (System.Text namespace), it has better memory allocation if your table changes in size.
da2.Fill(ds, "DNAiusTwitter_Table");
int counts = ds.Tables[0].Rows.Count;
StringBuilder appendString = new StringBuilder();
for (int i = 0; i < counts; i++)
{
appendString.AppendFormat("{0},", ds.Tables[0].Rows[i][3].ToString());
}
This will add all the data to the builder, then in the second code snippet, do the following to convert the builder to a string stripping off the additional comma at the end. Also I don't think you need the for loop (loop through 1?) in the second snippet or is the 1 in the for loop a typo?
var scrip = "var tweetUsers=['" + appendString.ToString().TrimEnd(new char[] { ',' }) + "'," + "'" + splitted[3]+"']";
use string.join() method
Example
string.Join(your_array, ",")

save the input value in a 2dimentsion array

how can i save the number that user enter in textbox in a 2 dimension array?
for example:
i have this numbers in textbox:45,78
and now i want to save 45,32 like this: array[0,0]=45 and array[0,1]=78
how can i do that?thanks,so much
edited:
oh,when i entered 1,2,3,4,5,6,7,8,9 in textbox and it takes [2,2]=56
private void button10_Click(object sender, EventArgs e)
{
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox9.Text.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i % (matrixDimention + 1), i % (matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
string a=intValues[2,2].ToString();
MessageBox.Show(a);
}
when i take:
string a=intValues[2,1].ToString();
it shows 0
Have a look at using String.Split Method (Char[]) and Convert.ToInt32 Method (String)
Something like
string textBox = "45,78";
int[,] values = new int[1,2];
string[] textBoxSplit = textBox.Split(',');
values[0, 0] = Convert.ToInt32(textBoxSplit[0]);
values[0, 1] = Convert.ToInt32(textBoxSplit[1]);
EDIT
Example using List and Linq
string textBox = "45,78,1,2,3,4,5,6,7,8,9,10,11,12";
List<int> list = new List<int>(textBox.Split(',').Select(x => Convert.ToInt32(x)));
EDIT 2
Longwinded example using List and foreach
string textBox = "45,78,1,2,3,4,5,6,7,8,9,10,11,12";
List<int> list2 = new List<int>();
string[] splitVals = textBox.Split(',');
foreach (string splitVal in splitVals)
list2.Add(Convert.ToInt32(splitVal));
EDIT
Enter the matrix
string textBox = "1,2,3,4,5,6,7,8,9";
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i/(matrixDimention + 1), i%(matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
EDIT
Follow the white rabbit
string textBox = "1,2,3,4,5,6,7,8,9";
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i/(matrixDimention + 1), i%(matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
string displayString = "";
for (int inner = 0; inner < intValues.GetLength(0); inner ++)
{
for (int outer = 0; outer < intValues.GetLength(1); outer++)
displayString += String.Format("{0}\t", intValues[inner, outer]);
displayString += Environment.NewLine;
}
MessageBox.Show(displayString);
try this assuming array is a string array
str[] input = textBox.Text.Split(',');
if(input.Length > 1)
{
arr[0,0] = input[0];
arr[0,1]= input[1];
}

Categories