How to add a string to a string[] array? There's no .Add function
You can't add items to an array, since it has fixed length. What you're looking for is a List<string>
, which can later be turned to an array using list.ToArray()
, e.g.
List<string> list = new List<string>();
list.Add("Hi");
String[] str = list.ToArray();
Trying to figure out how to add a string character to a string array using .Where
Where
doesn't work like this. It's a filtering device so it intrinsically cannot be used to extend/add to a list of things. The only thing you can do with a Where is prevent one of the input items being output, if some test returns false
For any given list of items;
string[] testArray = {"a", "b", "c", "d", "e"};
You can write a Where
, and pass to the Where
a small nugget of code (we tend to refer to it as a lambda) that is like a nameless method. It must accept one or two arguments and it must return a bool. Where
will loop over the input list of items, calling the lambda you passed on each one of the items. If the lambda returns true, the inputted item is output. If it returns false, the list item being looped is not output
These are the conceptual equivalents:
//this nice short thing
testArray.Where(s => s.Length == 1);
//is like this longer thing
public bool LengthIs1(string s){
return s.Length == 1;
}
...
foreach(var s in testArray)
if(LengthIs1(s))
output s; //this is a pretend thing: `output` doesn't exist but it means I don't also have to explain yield return. Just imagine that it sends the value out and carries on looping
Examples
testArray.Where(s => true); //every item will be output
testArray.Where(s => false); //no item will be output
testArray.Where(s => s == "a"); //only items equal to "a" will be output
testArray.Where(s => s.StartsWith("b")); //only items starting with b will be output
testArray.Where(s => DateTime.Now.DayOfWeek == DayOfWeek.Tuesday); //every item will be output if it's Tuesday, otherwise no item will be output
Those are examples that just take one argument s
, to the lambda. There is another form, the one you're using, where the lambda can have two parameters - the first parameter is again the item from the array. The second parameter is the index of the item in the array
testArray.Where((s,index) => true); //every item will be output
testArray.Where((s,index) => index == 0); //only the first item will be output
testArray.Where((s,index) => index != 1); //everything apart from the second item will be output
testArray.Where((s,index) => index%2 == 0); //even indexed items will be output
As you can see there isn't any scope for extending or adding more items. You start with 100 items, you can only output somewhere between 0 and 100 items
In the code you posted the first item is filtered out because the lambda assessed index versus index to remove, and will return true (keep) in all cases where they're not the same, and return false (remove) when they are the same
If you want to output more items you have to use something else, like Concat
new[]{1,2}.Concat(new[]{3,4})
This will output an enumeration of 1,2,3,4
Because Where
produces an enumerable thing, and Concat
can be called on an enumerable thing and accepts as a parameter another enumerable thing it means we could do something like:
testArray
.Where((s,index) => index != indextoremove)
.Concat(
testArray.Where((s,index) => index == indextoremove)
)
The first Where
excludes only the indextoremove
(it keeps the rest) and the second Where
keeps only the indextoremove
(it excludes the rest). The Concat
would just effectively take the first sequence, where "a" has been excluded and then concatenate on the second sequence where "a" is the only one included. This would essentially move "a" from the start, to the end of the sequence
It's horrifically inefficient, but this example is more about learning
(source, index) => index + indexremove(indextoadd)
This is, alas, flat out a syntax error. You've made indextoadd a string, and index to remove is an int. you can't follow an int variable name with a ( because you cannot execute/call an int. You this also cannot execute an int passing a string to it. As the final nail in the lambda's coffin, it's supposed to return a bool but you've done something approaching a numeric result, if int + int(string) was even possible. In full method terms you've done something like:
public bool AMethod(string source, int index){
string indextoadd = "a";
int indexremove = 1;
return index + indexremove(indextoadd);
}
Which hopefully you can see has a lot of syntax and logical problems..
How to add new elements to an array?
The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.
A better solution would be to use an ArrayList
which can grow as you need it. The method ArrayList.toArray( T[] a )
gives you back your array if you need it in this form.
List<String> where = new ArrayList<String>();
where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );
If you need to convert it to a simple array...
String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );
But most things you do with an array you can do with this ArrayList, too:
// iterate over the array
for( String oneItem : where ) {
...
}
// get specific items
where.get( 1 );
How to: Add a string to a string array using File.ReadAllLines
The error is caused since the length of the array is fixed and the and the last index (where you wanna add the new item) is always outside the array.
You can use a list instead:
public void CreateNewFolder()
{
List<String> lines = File.ReadAllLines(stringFile, Encoding.UTF8).ToList();
lines.Add("Test");
File.WriteAllLines(stringFile, lines.ToArray(), Encoding.UTF8);
//Calling the ToArray method for lines is not necessary
}
adding string array in existing session of array c#
Arrays can't grow in length, so you are better off using another data structure.
But if you insist on using arrays you need to create a new Array and then assign it to the session variable.
You can do something like this using Linq:
if (System.Web.HttpContext.Current.Session["Questions"] == null)
{
System.Web.HttpContext.Current.Session["Questions"] = Questions; // here question is string array,
//assigning value of array to session if session is null
}
else
{
string[] newQuestions = { "how are you?", "how do you do?" };
string[] existingQuestions = (string[])HttpContext.Current.Session["Questions"];
HttpContext.Current.Session["Questions"] = newQuestions.Union(existingQuestions).ToArray();
}
Adding values to a C# array
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).
Mutating to a new string array
something like this would do it. You don't have to do it this way...
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var newColl = new List<char>();
foreach(char c in "aaabbbccc".ToCharArray())
{
if (!newColl.Contains(c))
newColl.Add(c);
}
Console.WriteLine(new string(newColl.ToArray()));
}
}
Output:
abc
Array-only method
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const string orig = "aaabbbcccddd";
int origLen = orig.Length;
char[] newArr = new char[origLen]; // get max possible spots in arr
int newCount = 0;
for(int i = 0; i < origLen; i++)
{
bool yes = false;
for(int j = 0; j < newCount + 1; j++)
{
if (newArr[j] == orig[i])
{
yes = true;
break;
}
}
if (!yes)
{
newArr[newCount] = orig[i];
newCount++;
}
}
Console.WriteLine(new string(newArr));
}
}
Output:
abcd
Append a single character to a string or char array in java?
1. String otherString = "helen" + character;
2. otherString += character;
Related Topics
Should You Obfuscate a Commercial .Net Application
C# - Volatile Keyword Usage VS Lock
Hosting Clr in Delphi With/Without Jcl - Example
Is Configurationmanager.Appsettings Available in .Net Core 2.0
When Should One Use Dynamic Keyword in C# 4.0
How to Reference Microsoft.Office.Interop.Excel Dll
Is There Any Valid Reason to Ever Ignore a Caught Exception
Unzip a Memorystream (Containing the Zip File) and Get the Files
How to Display the Displayattribute.Description Attribute Value
Convert Int to a Bit Array in .Net
Write Values in App.Config File
Get Number of Listeners, Clients Connected to Signalr Hub
Get All Registered Routes in ASP.NET Core