what is the fastest way to transfer items from an array? [duplicate] - c#

This question already has answers here:
C# - For vs Foreach - Huge performance difference
(2 answers)
Closed 4 years ago.
Not sure if i phrased the title correctly but say i have a method such as:
public static string[] ByteArrayToStringArray(byte[] buffer)
{
//code here
}
would it be better to do
List<string> list = new List<string>();
for (int i = 0; i < buffer.Length; i++)
{
list.Add(buffer[i].ToString());
}
return list.ToArray();
or would it be better to do
List<string> list = new List<string>();
foreach (byte b in buffer)
{
list.Add(b.ToString());
}
return list.ToArray();
which is faster or is there no difference between them?

Like described in this question, iterating an array with a for loop is less cheaper than using a foreach.
You also could improve your code by omitting the list. Just create the array before and set the string items during the loop. Here is the improved version:
public static string[] ByteArrayToStringArray(byte[] buffer)
{
string[] ret = new string[buffer.Length];
for (int i = 0; i < buffer.Length; i++)
{
ret[i] = buffer[i].ToString();
}
return ret;
}
Note that there are also very compact LINQ options like
buffer.Select(c => c.ToString()).ToArray();
but LINQ queries are not best in terms of performance.
EDIT:
Referring to the discussion with Gusman at the comments below, it is possible to improve the performance even more by using a while loop.

Related

c# create a .forEach() Method using actions [duplicate]

This question already has answers here:
Why does assignment to parameter not change object?
(4 answers)
Closed 8 months ago.
I'm trying to create a method that loops through an array and executes some actions I wrote with a lambda expression. Somehow I don't think I understood how to use actions correctly because my code just results in a bunch of "null" objects.
Does somebody know what I am doing wrong?
public void forEach(Action<Neuron> action)
{
for(int i = 0; i < this.Neurons.Length; i++)
{
action(this.Neurons[i]);
}
}
public void CreateNeurons(int AmountOfNeurons)
{
this.Neurons = new Neuron[AmountOfNeurons];
this.forEach(x => x = new Neuron(AmountOfNeurons));
}
In your delegate, setting x = ... only changes the value of that local parameter: it does nothing to the array itself. You would end up with the same problem if you used a for loop like this:
var a = new[] { 1, 2, 3};
for (int i = 0; i < a.Length; i++)
{
var x = a[i];
x = 5; // this does nothing to `a[i]`
}
Notably, a foreach loop would warn you if you tried to do this:
foreach (var x in a)
{
x = 5; // CS1656: Cannot assign to 'x' because it is a foreach variable.
}
This supports Dai's comment: you really shouldn't be defining your own forEach method. There are plenty of better, more idiomatic ways to do anything you'd want to do with a method like this. A foreach construct would have told you exactly what you were doing wrong, for example. And creating an array with a bunch of items is typically simpler with LINQ:
this.Neurons = Enumerable.Range(0, AmountOfNeurons)
.Select(_ => new Neuron(AmountOfNeurons))
.ToArray();

How to prevent accidental modification of an array from the method? Without making the array immutable [duplicate]

This question already has answers here:
Are immutable arrays possible in .NET?
(10 answers)
Closed 3 years ago.
In the following method, how can I prevent the contents of my array from being modified accidentally or otherwise?
Can it be done without changing the array to another type, such as a list?
public static int LinearSearch(int[] myArray, int target)
{
int idx = -1;
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i] == target) { idx = i; break; }
}
return idx;
}
Use the ImmutableArray<T> class.
Provides methods for creating an array that is immutable; meaning it cannot be changed once it is created.
For instance:
ImmutableArray<int> array = ImmutableArray.Create(1, 2, 3);
You can also try the ReadOnlyCollection<T> class, that doesn't include a .Add method.

ForEach with index in C# [duplicate]

This question already has answers here:
List<T>.ForEach with index
(12 answers)
Closed 4 years ago.
I'm need to call function from ForEach in Linq, and I need to send a string parameter and the Index from the ForEach
List<string> listString= new List<string>();
listString.ForEach((str, i) => { Func(str, i) , i++});
private ResponseBase Func(string s,int i)
{
You could try something like this:
var responses = listString.Select((value, index) => Func(value, index)).ToList();
The above for each item in listString would call the method you have defined. The results of all calls would be stored in a list and you could access them by using the corresponding index.
I'm a big fan of LINQ. Really.
But in this cases, when you are accessing an already existing List, I would go for an old fashioned for loop.
for(var i = 0; i < listString.Count; i++)
Func(listString[i], i);
It's not longer, it's far more efficient (it's probably not a problem, but let's remember this), and it just gets the job done.
You can introduce a variable and then increment it:
List<String> values = new List<String>();
int indexTracker = 0;
values.ForEach(x=> { Func(x, indexTracker++); });
Or you can write the following extension method:
public static void ForEach<T>(this List<T> input, Action<T, int> action)
{
for(int i = 0; i < input.Count; i++)
{
action(input[i], i);
}
}
and then use it like
values.ForEach((x,i)=> Func(x, i));

C# increase length of a string array [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
how to inset a new array to my jagged array
i have a problem, where i dont know how i can make a string array variable in array length.
i have this code now below:
string[] p = new string[10];
int num = 0;
foreach (Product products in GetAllProducts())
{
//do something
p[num]= "some variable result"
num++
}
The problem is, that i dont know how many of "p" i will get, although i know it atleast will be less than 10.
but if i put it on 0, i will get an error when i start it, because it doesn't know the "p[num]"
So i am looking for some way to make "p" have a variable length.
anyone could help me out a bit? thanx
============Solved==========
List<string> p = new List<string>();
int num = 0;
foreach (Product products in GetAllProducts())
{
string s= null;
//do something ( create s out of multiple parts += s etc.)
p.add(s)
num++
}
thanx to solution poster
Use an List<string> instead of an array, if you do not know the number of items you will need to add.
Your array length cannot be modified after it has been instantiated. Use ArrayList or Generic Lists.
var p = new new List<string>(10);
foreach (Product products in GetAllProducts())
{
//do something
p.Add("some variable result");
}
What does GetAllProducts() return? Does it have a count or a length?! You should call that first, save it in a variable, get the count/length and then declare your array!
There's two solution.
If you want to keep using array :
int num = 0;
var list = GetAllProducts();
string[] p = new string[list.Length]; // Or list.Count if this is a collection
foreach (Product products in list)
{
//do something
p[num] = "some variable result";
num++;
}
Otherwise you should use a List like this :
List<string> p = new List<string>();
foreach (Product products in GetAllProducts())
{
//do something
p.Add("some variable result");
}
Use Array.Resize() method, which allows to resize it (by n number of indexes).
In my exmaple I will reize by 1 on each step of the way:
string[] array = new string[3]; //create array
for (int i = 0; i < 5; i++)
{
if (array.Length-1 < i) //checking for the available length
{
Array.Resize(ref array, array.Length + 1); //when to small, create a new index
}
array[i] = i.ToString(); //add an item to array[index] - of i
}
Because your code is using a foreach on the result from GetAllProducts, then GetAllProducts must be returning a IEnumerable collection. Probably the best solution would be to simply assign the result of GetAllProducts to such a collection. For example, perhaps it already returns a list of strings? So you can do:
List<string> strings = GetAllProducts();
There is no need to have a foreach loop to create an array when you already have a collection anyway being returned from GetAllProducts.
Or simply:
var strings = GetAllProducts();
to let the compiler work out the type of strings.
Most things you can do with an array you can also do with a List, and some more (such as adding items to the end of the List).
Perhaps you can post the signature of GetAllProducts (especially its return type) so we can better advise you?
I see many gave you the right answer which is the use of Lists. If you still need an array in the end, you can easily convert your list into an Array like this :
string[] tempArray = myList.ToArray();

C# Remove items from class array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Remove element of a regular array
I have a method defined which returns class array.
ex: Sampleclass[]
The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item.
for (int i = 0; i < Sampleclass.Length; i++)
{
if (Sampleclass[i].Address.Contains(""))
{
**// How to remove ??**
}
}
Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array:
var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString))
.ToArray();
It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following
var i = 0;
while (i < Sampleclass.Count) {
if (Sampleclass[i].Address.Contains("")) {
Sampleclass.RemoveAt(i);
} else {
i++;
}
}

Categories

Resources