I am just beginning with programming in c#;
I got a list of int variables that I want to sort, and find the number 1.
int Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9
do I need to do this with an array?
By using the yellow book of C# I found out how to make an array, but I can't figure out how to assign the variables to the array.
int [] Weapon_Count = new int [11] ;
for ( int i=0; i<11; i=i+1)
{
Weapon_Count [i] = ??? ;}
I hope this does make sense..
Please let me explain how to use a C#-array.
This creates an unitialized integer-array with 5 elements:
int[] a1= new int[5];
Assigning values 9,8,7,6 and 5:
(Please note that only indexes from 0 to 4 can be used. Index 5 is not valid.)
a1[0]=9;
a1[1]=8;
a1[2]=7;
a1[3]=6;
a1[4]=5;
The same can also achieved with just one line:
int[] a1= new int[] {9,8,7,6,5};
This might help you.
// Declaring the array
int[] Weapon_Count;
// Initializing the array with a size of 11
Weapon_Count = new int[11];
// Adding values to the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Weapon_Count[i] = i + 100;
}
// Printing the values in the array
for (int i = 0; i < Weapon_Count.Length; i++)
{
Console.WriteLine(Weapon_Count[i]);
}
// Same thing with a list
// Daclare and initializing the List of integers
List<int> weapon_list = new List<int>();
// Adding some values
weapon_list.Add(1);
weapon_list.Add(2);
weapon_list.Add(3);
weapon_list.Add(4);
weapon_list.Add(5);
// Printing weapin_list's values
for (int i = 0; i < weapon_list.Count; i++)
{
Console.WriteLine(weapon_list[i]);
}
// This is just for the console to wait when you are in debug mode.
Console.ReadKey();
Dont forget to include the using statment if you want to use lists (in short hand - dynamic arrays that can change in size.)
using System.Collections.Generic;
The easiest way to do this, assuming there is a finite list of variables to check, would be to throw them into a temporary array and call either Max() or Min() from the System.Linq namespace.
int maxCount = new int[] { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 }.Max(); // or .Min()
EDIT
If you still want to get those variables into an array, I would recommend using a System.Collections.Generic.List which has a dynamic size and helper methods such as .Add() to simplify things. Lists can also be used with Linq functions similar to the first part of my answer. See Dot Net Perls for some really good examples on different C# data types and functions.
EDIT 2
As #kblok says, you'll want to add using System.Linq; at the top of your file to gain access to the functions such as Max and Min. If you want to try using the List type, you'll need to add using System.Collections.Generic; as well. If you're in Visual Studio 2017 (maybe 2015 as well?) you can type out the data type and then hit Ctrl + . to get suggestions for namespaces that might contain that data type.
Before we start, you might edit your array to look like this:
int[] weapons = { Weapon_Count1, Weapon_Count2, Weapon_Count3, Weapon_Count4, Weapon_Count5, Weapon_Count6, Weapon_Count7, Weapon_Count8, Weapon_Count9 };
This means that you've created an array called weapons and it is holding integer values.
After you did this, lets find out which element in your array has value of number one.
To find which value has value "1" we must look at each element in array, and we might do that on few ways but I would like recommend foreach or for loop, in this case I will choose foreach loop.
foreach(var item in weapons)
{
if (item == 1)
//Do something
}
This above means, loop throught all of my elements, and in case some of them is equal to number one please do something..
P.S
(I may advice to create one variable which will hold an element which has value '1' and when you find it in a loop assing that variable to that element, and later you can do whatever you want with that variable.. and if you think there will be more elements with value of number one and you need all of them, instead of variable I mentioned above you will create list or array to hold all of your elements and also you can do later with them whatever you want to.)
Thanks and if you are interested in this kind of solution, leave me a comment so let me help you till the end to solve this if you are still struggling.
Related
I have this loop here, which for each question it is supposed to create, it generates and then formats a 'worded question' from an array of questions, such as; 'What is the sum of {0} + {1}?'. This loop then formats it, adds the worded question and the answer to an array.
// Use for loop to create the correct amount of questions
for (int i = 0; i < Data.Questions.numQuestions; i++)
{
Random rnd = new Random();
Data.Questions.Sum sum = new Data.Questions.Sum();
// Create part one and part two of the question using random numbers
// ex. 3 + 5
// 3 = partOne, 5 = partTwo
int partOne = rnd.Next(Data.Questions.Sum.min, Data.Questions.Sum.max);
int partTwo = rnd.Next(Data.Questions.Sum.min, Data.Questions.Sum.max);
// Randomly select one of the word questions
string fullQuestion = Data.Questions.Sum.wordedQuestions[rnd.Next(0, Data.Questions.Sum.wordedQuestions.Length)];
// Format the string with the generated numbers
fullQuestion = string.Format(fullQuestion, partOne, partTwo);
// Set out-of-class variables to be displayed to the user
Data.Questions.Sum.questions[i] = fullQuestion;
Data.Questions.Sum.answers[i] = partOne + partTwo;
}
Both Data.Questions.Sum.questions and Data.Questions.Sum.answers are List<string>'s and List<int>'s.
However, when this loop is run, with i = 0, I am thrown;
System.ArgumentOutOfRangeException: 'Index was out of range. Must be
non-negative and less than the size of the collection. Parameter name:
index'
Does anyone know what I'm doing wrong? As far as I know lists are dynamic, and I've defined like this;
// Arrays containing all questions and answers
// used to display questions and check answers
public static List<string> questions = new List<string>();
public static List<int> answers = new List<int>();
Also, to clarify, I do not want to use .Add(), as I have a settings panel which when you hit apply, re-runs this loop so the questions are up to date to the current settings. I need the loop to override the previous values.
Edit:
When using arrays, the better option here, I get;
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
On assigning Data.Questions.Sum.answers[i], after assigning the array like so; public static int[] answers {};
If you can't .Add() in this lists - create a copy of this lists and .Add() there. Lists has special for that kind of thing: new List<T>(IEnumerable<T>)
If you need to dynamically scale the collection, but you also need to iterate over it multiple times, then you'll need to check whether it is large enough to either insert, or just update.
You can do this with an extension method such as this...
public static class ListExtentions
{
public static void AddOrUpdate<T>(this List<T> that, int index, T value)
{
if (that.Count > index)
{
that[index] = value;
}
else
{
that.Add(value);
}
}
}
...which can then be called like this...
list.AddOrUpdate(index, value);
...however you can make things easier for yourself if you know how many questions you are going to have to start with.
If the number of questions changes when your UI changes, then you will also have to deal with the issue have scaling down the collection to ensure old elements are removed, which is much simpler if you just re-instantiate the collections every time you need to regenerate the questions / answers.
This is likly to be cause of your problem,(I have asked for clarification in comments where you didn't reply).
Still putting this as an answer, as it is potential error spot and you need to fix this.
As you mentioned you are facing this exception on i=0. there are high chanced that this is every time case not any specific case.
If Data.Questions.Sum.questions is empty then, Data.Questions.Sum.questions[i] = fullQuestion; , will surely throw such exception. Same way for Data.Questions.Sum.answers too.
In such case, you must use .Add() to insert into list.
so your code should be,
if (Data.Questions.Sum.questions.Count > i)
Data.Questions.Sum.questions[i] = fullQuestion;
else
Data.Questions.Sum.questions.Add(fullQuestion);
But if they are not empty, it must not be the cause of this exception.
One more thing i have noticed in your code is Data.Questions.Sum.wordedQuestions.
Even if you have valid list (here Data.Questions.Sum.wordedQuestions) - as you have Length prop, it must be Array not list.
If it is empty, while doing this
string fullQuestion = Data.Questions.Sum.wordedQuestions[rnd.Next(0, Data.Questions.Sum.wordedQuestions.Length)];
this line will surely throw
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
as you are trying to get 0th index's data from it.
So before fetching data from list or array, first you need to check if it does have data init, and also it does have that index which you are asking.
something like
string fullQuestion = string.Empty;
if (Data.Questions.Sum.wordedQuestions != null &&
Data.Questions.Sum.wordedQuestions.Length > 0)
{
//here the way you are creating random number,
// you are assured about index is present in array.
int indexForWordedQuestion = rnd.Next(0, Data.Questions.Sum.wordedQuestions.Length);
fullQuestion = Data.Questions.Sum.wordedQuestions[indexForWordedQuestion];
}
I just have a question. I noticed that unlike C++, C# is a bit complicated when it comes to array. One of the features or techniques I've been looking for in the array is that: I want to add elements or remove elements from it in a more efficient and simpler way.
Say for example, I have an array called 'food'.
string[] food = {'Bacon', 'Cheese', 'Patty', 'Crabs'}
Then I decided to add more food. Problem with C# as I can see it is this isn't possible to do unless you do use an ArrayList. How about for an array itself? I want to use the array as some sort of inventory where I add things.
Thanks a lot!
You can't do that with arrays in C# without allocating a new array. Because arrays are fixed in size.
If you want to be able to add/remove elements from a container, you could use List<T>. Alternativly you could use an ArrayList but that is not recommended, since in most cases List<T> has a performance advantage.
Internally both use an array as the default container for your data. They also take care of resizing the container according to how much data you put in the collection or take out.
In your example, you would use a list like
List<string> food = new List<string> { "Bacon", "Cheese", "Patty", "Crabs" };
food.Add("Milk"); //Will add Milk to the list
food.Remove("Bacon"); //Will remove "Bacon"
List on MSDN: Docs
Ideally, if you are going to have a variable size array of strings, a List would be better. All you would have to do is then call list.Add(""), list.Remove(""), and other equivalent methods.
But if you would like to keep using string arrays, you could create either a function or class that takes an array, creates a new array of either a larger or smaller size, repopulate that array with the values you had from the original array, and return the new array.
public string[] AddFood(string[] input, string var)
{
string[] result = new string[input.Length + 1];
for (int i = 0; i < input.Length; i++)
{
result[i] = input[i];
}
result[result.Length - 1] = var;
return result;
}
public string[] RemoveFood(string[] input, int index)
{
string[] result = new string[input.Length - 1];
for (int i = 0; i < input.Length; i++)
{
if (i < index) {
result[i] = input[i];
}
else
{
result[i] = input[i + 1];
}
}
return result;
}
Again, I would highly recommend doing the List method instead. The only down side to these lists is that it appends them to the end, rather then figuring out where you want to place said items.
List<string> myFoods = new List<String>(food);
myFoods.Add("Apple");
myFoods.Remove("Bacon");
myFoods.AddRange(new string[] { "Peach", "Pineapple" });
myFoods.RemoveAt(2);
Console.WriteLine(myFoods[0]);
There is also ArrayList if you want a list more like an array, but it is older code and unfavoured.
ArrayList myFoods = new ArrayList(food);
myFoods.Add("Apple");
myFoods.Remove("Bacon");
myFoods.AddRange(new string[] { "Peach", "Pineapple" });
myFoods.RemoveAt(2);
Console.WriteLine(myFoods[0]);
I hope this helps.
To actually answer the question, you just need to resize the array.
Array.Resize(ref array, );
is the new length of the array
To really add elements to an existing array without resizing you can't. Or, can you? Yes, but with some trickery, which at some point you might say is not worth it.
Consider allocating an array of the size you anticipate it could be. You obviously have to estimate well to avoid tons of unused space. Empty slots in the array would be marked by a sentinel value; for a string the obvious candidate is null. You'd know the "true" size of the array by keeping track of the first index of the sentinel. This suggests that an ArrayWrapper class would encapsulate the array and "true size".
That wrapper could add Add() and AddRange() that replace the sentinel values with real ones without allocating.
All that said, the drawback at some point will be that you have to allocate a new array. Doing this manually using the wrapper is pointless unless you have very specific requirements that allow you to reduce allocations.
So, for the most common cases, stick to a List<>, which does that for you. With the list you can construct it by calling the constructor that takes an initial capacity parameter. Adds will use the underlying array without reallocation until it hits the limit.
In a way that List<> is your wrapper that uses an allocation model the original authors decided would minimize allocations in most cases. That is likely to perform better than anything you write unless you can really leverage your domain.
I'm now doing a project about solving a Magic cube problem. I want to create an array to remember the steps like this:
char[] Steps = new char[200];
Each time I do the 'F','B','R','L','U','D' turn method, it will add a 'F','B','R','L','U','D' character in the array.
But when I want to get the length of the steps, it always shows 200.
for example:
char[] steps = new char[5];
and now I've already added 3 steps:
steps[] = {'f','b','f','',''};
How can I get the length '3'?
Or is there any alternative method I can use that I don't need to set the length at the beginning?
you can just use List<char> but if performance is really critical in your sceanario you can just initialize the initial capacity
something like the following
List<char> list = new List<char>(200);
list.Add('c');
list.Add('b');
here count will return just what you have really added
var c = list.Count;
note in list you can apply Linq Count() or just use the Count property which does not need to compute like Linq and return the result immediately
You will get compilation error on this line
steps[] = {'f','b','f','',''};
As you cannot use empty char and you need to write steps instead of steps[].
I will suggest you to use string array instead and using LINQ get count of not empty elements in this way:
string [] steps = {"f","b","f","",""};
Console.WriteLine(steps.Where(x=>!string.IsNullOrEmpty(x)).Count());
To count non-empty items using System.Linq:
steps.Count(x => x != '\0');
Your code doesn't compile since '' isn't allowed as a char, but I'm assuming that you mean empty elements in a char array which are actually represented by '\0' or the Unicode Null. So the above condition simply counts the non null items in your array.
you could use a list of character that would make things a lot simpler like this :
List<char> steps = new List<char>();
and just add a line to the list for each steps :
char move = 'F';
steps.add(move);
finally then you can count the number of move in the list easily
int numberofmove = steps.count();
This question already has answers here:
Most efficient way to append arrays in C#?
(11 answers)
Closed 8 years ago.
Background on the program: the heart of the program needs to track all other Forms or other elements of the program. To do this, I am using a Form array
What I am wanting to do is take my initially defined array containing 1 element, and increase the length of the array to add a new element whenever a new Form is launched.The trouble I've run into is that I can't find out how to do this without using a second array to store the old array, re-declaring the original array with array.length += 1, looping through to re-add the original content from the second array, then adding the new element. It's heavy and inconvenient since I need to use similar processes elsewhere.
The code I have, which works but is ugly, is this:
public class PCB
{
Form[] Runners;
public PCB()
{
Runners = new Form[1];
Runners[0] = new GUI;
.
.
.
.
.
void NewForm(Form app)
{
Form[] TEMP = Runners; //Create my new array equal to the first
Runners = new Form[Runners.Length + 1]; //re-create the old array, with an additional element
for (int k = 0; k < TEMP.Length; k++)
{
//add the original elements back to the original array
Runners[k] = TEMP[k];
}
Runners[TEMP.Length] = App; //add the final element to the array
I hate having to use the loop-structure, as I feel that it can be done cleaner. what I'm looking for is a function similar to the ListBox.Items.Add([[ITEM]]), but for an array.
Does such a function exist, or do I need to continue with my ugly loops?
Use a list instead:
List<Form> Runners = new List<Form>();
...
Runners.Add(app);
If you for some odd reason absolutely must use an array, then Array.Resize is what you're looking for, but a list is much better.
I believe what you're looking for is a List. A List already does this for you under the hood in .NET. You can do this:
List<Form> Runners;
Runners = new List<Form>();
Now when you add to the list you can do:
Runners.Add(new MyForm());
When you want to remove from the list you can do:
Runners.Remove(MyForm);
Just use a List<Form> list instead of arrays, which can be accessed just like an array and you can dynamically add other elements (list.Add(new Form(...))).
It is much more performant than an array and it has other features that can simplify your coding.
One way is to use Array.Resize
P.S. !!! be sure that the references to your array won't be changed.
Here is an example:
using System;
class aaa
{
static void Main()
{
string[] array = new string[10];
Array.Resize(ref array, 20);
}
}
how to get direct value from a list that contain an array ?
hey guys ,
i want to directly get a certain value from a list that contain an array
List<int[]> myList = new List<int[]>();
myList.Add( new int[2] { 10, 11 } );
its clear for me to get this using foreach loop like
foreach ( int[] p in mylist)
console.write(p[0]);
i do want to retrive this single data using expression like list[0] for list of integers
thanks..
Your question is very unclear, but if you know the array index within the array, you can use:
int value = myList[listIndex][arrayIndex];
Effectively this is just doing:
int[] array = myList[listIndex];
int value = array[arrayIndex];
im not entirely sure what you mean . . .
it would look like a 2d array: myList[position of array in list][position of item in selected array]. this is because a list is generic container and the overloaded bracket operator will return the specific type (which in this case is an array), that then enables you to use the bracket again to refer to the items contained in the array.
the snipplet you wrote actually only iterates the first item foreach array in your list (was this on purpose)?
in essence, you kind of need 2 pieces of information unless you only want the first item in each list (position 0) in which case you would create a new container class, implement the IList interface and overload the bracket operator like this:
public int this[int index]
{
get
{
return myList[index][0];
}
set
{
myList[index][0] = value;
}
}