How to make arrays values equal in C#? - c#

Let's say that I have 2 string arrays with different values:
string[] sArray1 = new string[3]{"a","b","c"};
string[] sArray2 = new string[3]{"e","f","g"}
And I want to make values of sArray1 equal to values of sArray2 (I know I can write it like this) : sArray1[0] = sArray2[0]; sArray1[1]= sArray2[1]; sArray1[2]=sArray2[2];
For 3 values it's easy, but what if I had 100 values in an array? Is there any other way that I can make array values equal?
p.s. sorry for my bad English :(

Something like this (with a little error checking):
if (sArray2.Length == sArray1.Length)
{
sArray2.CopyTo(sArray1, 0);
}
Regards

I'm assuming you want to keep the reference to the original array in sArray1? Then do this:-
Array.Copy(sArray2, sArray1, sArray1.Length);

If you want them to function independently of each other than you can use .Clone() as of .NET 5.0
string[] sArray1 = (string[])sArray2.Clone();
In the above scenario if you change a value in one array it will not affect the other - this is called a "shallow copy" (AKA copy by val). If you want the values in both arrays to be tied to each other (typically not desirable) you can do a simple assignment like this:
string[] sArray1 = sArray2;
In this case if you change a value in either array the value(s) in the other array will update (AKA copy by ref).

Related

Is it possible to get array length inline

I have to access Dictionary<TKey, TValue> value by key (that I get from array I'm creating inline) like so:
var someString = "1.2.3";
someDictionary[someString.Split('.').ToArray()[ /---> self.Length <---/ - 1 ]];
Question: Is it possible to get array Length inline without creating new variable and assigning array to it?
You cannot do this. You need to store intermediate value in a variable if you want to access it twice.
I see no sense in trying to do this without additional variable - at least, your approach is absolutely unreadable.
However, as I understand, by [self.Length - 1] you want to access the last value in this array.
If yes, then you can just use LINQ .Last:
var someString = "1.2.3";
someDictionary[someString.Split('.').Last()]; // someDictionary["3"]

setting variable in if statement, then told it's unassigned

I want to initialize an array--I don't know how big it will be. then set it in a condition
so I've got:
string[] my_string;
if(x==2)
{
my_string=File.ReadAllLines("file.txt");
}
string new_string=my_string[1];
It's telling me I've an unassigned local variable, because it's in the condition. How do I get around this?
You need to make sure it has a value if x isn't 2.
At the moment, if x is not equal to 2, then you have no values in your array, but you're still calling that array anyway. One thing you could do is move the new_string assingment inside the if statement. Of course, this may not be the best method if you have other values of x you watch to check against. If so, a Switch..Case might be better.
string[] my_string;
//set new_string to be empty for now
string new_string = String.Empty;
if(x==2)
{
my_string=File.ReadAllLines("file.txt");
//Make sure there are at least two elements
if(my_string.Length >= 2)
//Get the second element of the array (remember, 0 is the first element)
new_string = my_string[1];
}
Why not Create a List instead and then utilize the File.ReadAllLines("file.txt")
also are you including the FilePath along with file.txt
here is a free code snippet for you to use I use this alot when I want to load a TextFile into a List as one bulk load...
List<string> lstLinesFromFile = new List<string>(File.ReadAllLines(yourFilePath+ "file.txt"));
from there you can check in the debugger or add a quickwatch to lstLinesFromFile and see all the text that was loaded. each line from there will be accessed link ordinal so use a for loop or foreach loop

Declaring an array with incremental values - is there a shortcut?

This question is probably pretty stupid, but I'm new to C# and I'm not sure if there are any shortcuts to do this. I have a dynamic array for which the range will always be 1-n, with n being variable. Is there anyway to declare an array and have it hold incremental values without looping?
Think along the lines of my array holding values 1-50. I'd like to declare an array as such (logically): double[] myArray = new double[] {1-50} or, more generically for my purposes double[] myArray = new double[] {1-n}. I don't know what made me think of this, I just thought I'd ask.
I am going to bind this array (or list) to a combo box in WPF. I guess setting a combo-box the same way would also work if there's a shortcut for that.
Sorry for the dumb question. =)
int n = 50;
var doubleArray = Enumerable.Range(1, n).Select(x => (double)x).ToArray();
That will generate a sequence of integers from 1 to n (in this case 50) and then cast each one to a double and create an array from those results.
You could use a List<T> which represents a dynamic array to which you could add elements.
System.Linq.Enumerable.Range can generate än enumeration of int. Cast the enumeration if you really want double.
System.Linq.Enumerable.Range(1,20).ToArray()
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx

NULLs in string array

How to remove Null values in string array
Like { ,-2,3, ,-4,+5, ,66...}
I need to remove those null values in between and re-size the array
I don't want to use lists
I don't want to create a new array
Please let me know if it is possible with simple code.
Thank You.
No, it's not possible without creating a new array. You can't resize an array.
You can easily create a new array without empty strings and null references like this:
string[] items = new string[] { "", "-2", "3", null, "-4", "+5", null, "66" };
items = items.Where(s => !String.IsNullOrEmpty(s)).ToArray();
If you don't want to create a new array, then no, it's not possible. You cannot add or remove an item from a simple array (as in, string[]).
The most straightforward way to accomplish what you want to achieve (if you remove your second requirement) would be:
Count the number of null values in your source array
Create a new array of the same length as your source array minus the number of nulls from step 1
Copy all non-null values from your source array into the new array
(Optional) Set the reference to your source array (e.g., srcArray) to your new array
As Dan said, you can't add or remove values from an Array. You can, however, use LINQ to remove the values and produce a second array.
originalArray = originalArray.Where(s => !string.IsNullOrEmpty(s)).ToArray()
Probably not the most performant solution but...
array.Where(s => s != null).ToArray();
It will create a new array, but I cannot think of a solution that won't.
Before deciding how to proceed, you really need to think about who holds a reference to the array you are operating on.
If the array is not referenced by any other code (as a member of a class, as a captured variable in a lambda, or in some collection somewhere) then you shouldn't worry about creating a new array. In that case I would use something like what #Codesleuth or #Guffa suggest.
However, if other code may exist that holds a reference to this same array - then you are out of luck, unless you can safely identify and update the references held in those other places. This is a hard thing to do - and you should be very careful assuming that you can always update all other places where a reference is held.
Am I the only one here that would scan the array and move the members back over the NULLs, therefore making a continuous list of non-nulls.
This doesn't create a new array and it's simple to implement and it's immportant to know you can move the entries around the array.
Unfortunately I'm at work so can not supply full code, however you would implement it by searching the array for NULLs then moving the remaining items in the array up one. Keep doing this until the end. I would suggest clearing the remaining entires once the search is completed.
string[] _array= new string[] { "", "z", "d", null, "a", "b", null, "66" };
// select non-null elements only
_array= _array.Where(a => !String.IsNullOrEmpty(a)).ToArray();

Array of an unknown length in C#

I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Arrays must be assigned a length. To allow for any number of elements, use the List class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Use List<> to build up an 'array' of unknown length.
Use List<>.ToArray() to return a real array, and not a List.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.
Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.
Search for them in System.Collections and System.Collections.Generics.
You might also want to look into Dictionarys if your data is unique, This will give you two columns to work with.
User name , Total bill
it gives you a lot of built in tools to search and update just the value.
var yummy = new List<string>();
while(person.FeelsHappy()) {
yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
"until I finished making it!");
try a generic list instead of array
In a nutshell, please use Collections and Generics.
It's a must for any C# developer, it's worth spending time to learn :)
As detailed above, the generic List<> is the best way of doing it.
If you're stuck in .NET 1.*, then you will have to use the ArrayList class instead. This does not have compile-time type checking and you also have to add casting - messy.
Successive versions have also implemented various variations - including thread safe variants.
If you really need to use an array instead of a list, then you can create an array whose size is calculated at run time like so...
e.g i want a two dimensional array of size n by n. n will be gotten at run time from the user
int n = 0;
bool isInteger = int.TryParse(Console.ReadLine(), out n);
var x = new int[n,n];

Categories

Resources