Confusion in using Arrays in C# - c#

is it possible to accept more than one entires,as variables, and then change it to an array! as for example, the user would enter more than one name, but not defined how many names they should enter, and when I received the names I would change it to an array, is that possible ?
Thanks!

In .NET arrays have fixed length. If you want to be able to dynamically add elements to a list you could use the List<T> class.
For example:
List<string> names = new List<string>();
Now you could start adding elements to the list:
names.Add("foo");
names.Add("bar");
names.Add("baz");
And you could also get the corresponding fixed length array using the ToArray() method:
string[] namesArray = names.ToArray();

I think what you're looking for is the param object []. It's used for an undetermined number or parameters into a function. Your function would go like this:
public static void SayHello(params string[] names){
foreach(var name in names){
Console.WriteLine("Hello " + name);
}
}
And you could call it like this:
SayHello("Bob", "Bill", "Susan");
SayHello("Jenny");

If the user is going to enter more than one name, then I suggest you create a list of strings instead of an array.

Related

C# getting array with a string name?

So here's a hypothetical. From someone fairly new to the whole C# and Unity thing:
Suppose for a moment that I have a series of string[] arrays. All of which have similar naming convention. For example:
public string[] UndeadEntities =
{
// stuff
};
public string[] DemonEntities =
{
// stuff
};
Now suppose I want to call one of them at random, I have another list that contains the names of all of those arrays and I return it at random.
My problem is that I grab the name from the array and it's a string, not something I can use. So my question is this:
is there any way for me to use this string and use it to call the above mentioned arrays.
Something like this is what I'm up to but unsure where to go from here and I really would like to avoid making a massive series of If Else statements just for that.
public string[] EnemiesType = { // list of all the other arrays }
public string enemiesTypeGeneratedArrayName = "";
public void GenerateEncounterGroup()
{
enemiesTypeGeneratedArrayName = EnemiesType[Random.Range(0, 12)];
}
Can I nest arrays inside of other arrays? Is there another alternative?
I'm not sure if it is possible at all but if it is, I'll take any pointers as to where to go from there. Thanks.
There are several solutions to your specific problem, an easy one is using Dictionaries:
A Dictionary is a data structure wher you have a key (usually a string) and a value (whatever type you may want to store).
What you can do is at start, initialized a Dictionary were each key is your enemy type, and the value it store is your array, something like:
Dictionary<string, string[]> enemyArrays= new Dictionary<string, string[]>();
.
void Start()
{
enemyArrays["typeA"] = myArrayA;
enemyArrays["typeB"] = myArrayB;
}
Then when you need to get that array, just:
enemiesTypeGeneratedArrayName = EnemiesType[Random.Range(0, 12)];
string[] myRandomArray =enemyArrays[enemiesTypeGeneratedArrayName];
string randomEnemy = myRandomArray[index];
Here you can read more about Dictionary class if you want.
There are other ways to do it, but I think this one is pretty easy to implement in the code you already made, and Dicionaries are cool haha.
I hope is clear:)

Store process output in array

I initiated an empty array - line.
string[] line = new string[] { };
I want to store every line that would be outputed in a cmd processing with the while loop below. This seems to work easily if I store the values in a string variable.
As shown below:
while (!proc.StandardOutput.EndOfStream)
{
line = proc.StandardOutput.ReadLine();
}
However, I'm not sure how to store the values as separate elements in the array. I've tried:
while (!proc.StandardOutput.EndOfStream)
{
for(a in line)
{
a = proc.StandardOutput.ReadLine();
}
}
But its not working.
This is probably a very basic question. But I'm still learning C#.
There are few solutions. One would be to use List<string> instead of string[]:
List<string> line = new List<string>();
And than add lines next way:
while (!proc.StandardOutput.EndOfStream)
{
line.Add(proc.StandardOutput.ReadLine());
}
An array works on the basis of indexing. So if you want to use an array you need to specify how long it has to be or in other words how many items it can contain:
// this array can store 100 items
string[] line = new string[100];
To access a certain position you need to use the [ ] operator and to move forward in the array you need an indexing variable of type int that you can increment each iteration
int indexer = 0;
while (!proc.StandardOutput.EndOfStream)
{
line[indexer] = proc.StandardOutput.ReadLine();
indexer ++; // increment
}
This way you need to know in advance how many items you want to deposit in your array.
Another way would be to use a flexible collection like List which can dynamically grow. Sidenote: The indexing works with the same [ ] operator, but the adding of items works via the Add method
If you want to know more have look at this overview of possible collection types

Why do I get an error when List<object>.Add(int)

I have an array of List types:
List<object>[] vector = new List<object>[3];
The first List contains strings:
// Get word lists together, remove duplicates
var words = tableA.ToList().Union(tableB.ToList());
// Sort words
words = words.OrderBy(s => s, StringComparer.CurrentCultureIgnoreCase);
// Add words to the vector first slot
vector[0] = words.ToList<object>();
Now, I want to add ints to the second and third lists, but I get an error here:
vector[1].Add(tableA.GetValue(keyword));
vector[2].Add(tableB.GetValue(keyword));
GetValue() returns an int. But when I add these ints to the vector Lists it throws error:
ERROR Caught: Object reference not set to an instance of an object.
How should I add the ints to the List? Or is there some other data structure I should use instead for the vector? I feel there is some trivial cast I'm missing but I haven't been able find a solution.
I'm not an expert in C#, but i think i understand.
When you write :
List<object> vector = new List<object>[3];
you create a table of List with a size of 3.
You can put something into each slot of this array, but each "slot" still refers to no instance after this first line of code.
When you write
vector[0] = words.ToList<object>();
You put somehting into the first slot of vector list. But [1] and [2] are still empty. And
vector[1]
refers to a reference not set to an instance of an object. In short terms, it refers to nothing.
You must initialize each vector index value before add value. Thanks
When writing var a = new List<object> you´re only declaring that a is a list holding some (in your case three) items. However you don´t determine what stands in those three elements. You´d have to out some values into every single item, before you can anything with it (e.g. call any method).
You´re allready putting a list into the first item, however the elements on index one and two remain null causing a NullReferenceException when calling a method like the following:
vector[1].Add(...);
So you should initialize the value at index oe and two before:
vector[1] = new List<int>();
vector[2] = new List<int>();
But still you can´t do much with the list, because it is of type object, so you´d have to cast every element to the actual type:
((List<int>)vector[1]).Add(myInt);
Anyway I doubt storing three completely different lists within one single list alltogether is a good idea. Maybe you should define a class with the three lists as members instead:
class MyClass
{
public List<string> Words { get; set; }
public List<int> NumbersA { get; set; }
public List<int> NumbersB { get; set; }
}

Check if Characters in ArrayList C# exist - C# (2.0)

I was wondering if there is a way in an ArrayList that I can search to see if the record contains a certain characters, If so then grab the whole entire sentence and put in into a string. For Example:
list[0] = "C:\Test3\One_Title_Here.pdf";
list[1] = "D:\Two_Here.pdf";
list[2] = "C:\Test\Hmmm_Joke.pdf";
list[3] = "C:\Test2\Testing.pdf";
Looking for: "Hmmm_Joke.pdf"
Want to get: "C:\Test\Hmmm_Joke.pdf" and put it in the Remove()
protected void RemoveOther(ArrayList list, string Field)
{
string removeStr;
-- Put code in here to search for part of a string which is Field --
-- Grab that string here and put it into a new variable --
list.Contains();
list.Remove(removeStr);
}
Hope this makes sense. Thanks.
Loop through each string in the array list and if the string does not contain the search term then add it to new list, like this:
string searchString = "Hmmm_Joke.pdf";
ArrayList newList = new ArrayList();
foreach(string item in list)
{
if(!item.ToLower().Contains(searchString.ToLower()))
{
newList.Add(item);
}
}
Now you can work with the new list that has excluded any matches of the search string value.
Note: Made string be lowercase for comparison to avoid casing issues.
In order to remove a value from your ArrayList you'll need to loop through the values and check each one to see if it contains the desired value. Keep track of that index, or indexes if there are many.
Then after you have found all of the values you wish to remove, you can call ArrayList.RemoveAt to remove the values you want. If you are removing multiple values, start with the largest index and then process the smaller indexes, otherwise, the indexes will be off if you remove the smallest first.
This will do the job without raising an InvalidOperationException:
string searchString = "Hmmm_Joke.pdf";
foreach (string item in list.ToArray())
{
if (item.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
list.Remove(item);
}
}
I also made it case insensitive.
Good luck with your task.
I would rather use LINQ to solve this. Since IEnumerables are immutable, we should first get what we want removed and then, remove it.
var toDelete = Array.FindAll(list.ToArray(), s =>
s.ToString().IndexOf("Hmmm_Joke.pdf", StringComparison.OrdinalIgnoreCase) >= 0
).ToList();
toDelete.ForEach(item => list.Remove(item));
Of course, use a variable where is hardcoded.
I would also recommend read this question: Case insensitive 'Contains(string)'
It discuss the proper way to work with characters, since convert to Upper case/Lower case since it costs a lot of performance and may result in unexpected behaviours when dealing with file names like: 文書.pdf

String.Format - Problem with Argument list

string nr = "42245555" //just an example number
string expression = "{5}{6}/{7}{8}";
string res = String.Format(expression, new string[] {
nr[0].ToString(),nr[1].ToString(),
nr[2].ToString(), nr[3].ToString(),
nr[4].ToString(), nr[5].ToString(),
nr[6].ToString(), nr[7].ToString()
});
Why is this not working and how can I solve it?
I want expression to be either "{5}{6}/{7}{8}" or "{0}{3}/{7}{1}" or whatever the user wants.
You must supply at least the same number of parameters (or an array with at least the same number of elements) as the highest placeholder value plus one (placeholder values are zero indexed)
Max placeholder value {3}, you must supply at least four additional parameters.
Try this:
string res = String.Format(expression,
nr[0], nr[1],
nr[2], nr[3],
nr[4], nr[5],
nr[6], nr[7]);
Note that I took out new string[] { ... } I also took out all the ToString() because they are not required.
The relevant overload of Format is:
public static string Format(string format, params Object[] args)
This means you can either call it like this:
Format("...",new object[]{...})//Each array element is used
Or with the objects directly as parameters:
Format("...",object1, object2,...)//the objects are used
Unlike what I originally thought, a string[] does indeed go into the first variant of this code. This is due to array covariance in C#/.net which allows a string[] to be implicitly converted to a object[].
string.Format("{0} {1}",new string[]{"A","B"})
prints A B.
On the other hand if you try similar code with a int[] it won't work:
string.Format("{0} {1}",new int[]{1,2})
Will throw an exception because it goes into the second variation, and thus only a single parameter of type int[] is seen by string.Format. This difference is because array covariance only works on arrays with members that are a reference type like string and not a value type like int. This means int[] is not implicitly convertible to object[].
So the problem with your original code is probably just that you used the index {8} which is out of range.
The parameters in expression must start from "{0}" and the array must contain the same number of parameters as the expression and it must be an array of objects : new object[]{...
Your parameters are numbered 0..7, easy to read back. Yet you use {8} : Index out of Range
You don't need the new string[] { } around the parameters. It is allowed though.
without the new string[] { } you don't need the .ToString() calls either.
IF ur user wants {5}{6}/{7}{8} , then ur code will be:
String.Format("{0}{1}/{2}{3}",nr[4],nr[5],nr[6],nr[7]);
ur indexes in the expression must always start with 0..In my example if u want to display this for strings.. u start by 0,1,2,3.. 0 for nr[4], 1 for nr[5], 2 for nr[6], 3 for nr[7], etc..
You have to use:
nr.Substring(...)
in String.Format([expression], [values]) expression is a string represent a string with placeholders while values are inserted in those placeholders.
updated
string nr = "42245555" //just an example number
string res = String.Format("{0}{1}/{2}{3}", new string[] {
nr[5].ToString(),nr[6].ToString(),
nr[7].ToString(), nr[8].ToString()
});
or
string res = String.Format("{0}{1}/{2}{3}", new string[] {
nr[0].ToString(),nr[3].ToString(),
nr[7].ToString(), nr[1].ToString()
});

Categories

Resources