Array slices in C#
Arrays are enumerable, so your foo
already is an IEnumerable<byte>
itself.
Simply use LINQ sequence methods like Take()
to get what you want out of it (don't forget to include the Linq
namespace with using System.Linq;
):
byte[] foo = new byte[4096];
var bar = foo.Take(41);
If you really need an array from any IEnumerable<byte>
value, you could use the ToArray()
method for that. That does not seem to be the case here.
Correct form to Slice an Array In C#
I think the best way to treat your approach would be with IEnumerable objects, specifically using LINQ.
IEnumerable is an interface meaning "you can call foreach on this object". It's implemented for arrays, and also for some other objects used to query collections - part of the point being, you don't especially need to know WHAT those objects are; just enumerate each item when you need them.
using System.Linq; // put this at the top of the .cs, not mid-code.
int startIndex = 0;
int lenght= 5;
IEnumerable<int> CopyArray = Original.Skip(startIndex).Take(lenght);
I wrote that in notepad, so it's possible there's some small thing I missed, but that should give you what you need. You can skip the .Skip(startIndex) part if it's always going to be 0. To access each int:
foreach (int value in CopyArray) {
// TODO with value??
}
Can't slice an array in c#
That is because the range operator
[n..m] is available for version C# 8.0 or greater
This might be useful too
Target framework version C# language version default
.NET Core 3.x C# 8.0
.NET Core 2.x C# 7.3
.NET Standard 2.1 C# 8.0
.NET Standard 2.0 C# 7.3
.NET Standard 1.x C# 7.3
.NET Framework all C# 7.3
If upgrading is not an option you can use:
int[] array = { 1, 2, 3, 4, 5 };
var t = array.Take(2);
Readable C# equivalent of Python slice operation
The closest is really LINQ .Skip()
and .Take()
Example:
var result1 = myList.Skip(2).Take(2);
var result2 = myList.Skip(1);
var result3 = myList.Take(3);
var result4 = myList.Take(3).Concat(myList.Skip(4));
C# Array slice without copy
Change the method to take an IEnumerable<T>
or ArraySegment<T>
.
You can then pass new ArraySegment<T>(array, 5, 2)
How to slice elements from 2nd item in a c# array?
You can use C# 8 indices and ranges feature
double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
var slice = arr[1..];
It'll return all items from index 1 till the end of array and give you an expected slice {3, 2, 8, 7, 6, 1 }
. Again, it works only with C# 8 and .NET Core 3.x.
For earliest versions of C# you should do this by yourself, using Array.Copy
for example or System.Linq
double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
var slice = arr.Skip(1).ToArray();
Two dimensional array slice in C#
There's no direct "slice" operation, but you can define an extension method like this:
public static IEnumerable<T> SliceRow<T>(this T[,] array, int row)
{
for (var i = 0; i < array.GetLength(0); i++)
{
yield return array[i, row];
}
}
double[,] prices = ...;
double[] secondRow = prices.SliceRow(1).ToArray();
How do I clone a range of array elements to a new array?
You could add it as an extension method:
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
static void Main()
{
int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}
}
Update re cloning (which wasn't obvious in the original question). If you really want a deep clone; something like:
public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
T[] arrCopy = new T[length];
Array.Copy(data, index, arrCopy, 0, length);
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, arrCopy);
ms.Position = 0;
return (T[])bf.Deserialize(ms);
}
}
This does require the objects to be serializable ([Serializable]
or ISerializable
), though. You could easily substitute for any other serializer as appropriate - XmlSerializer
, DataContractSerializer
, protobuf-net, etc.
Note that deep clone is tricky without serialization; in particular, ICloneable
is hard to trust in most cases.
Related Topics
How to Use Linq with a MySQL Database on Mono
Get a Screenshot of a Specific Application
Keeping ASP.NET Session Open/Alive
Error: "Cannot Modify the Return Value" C#
Design - Where Should Objects Be Registered When Using Windsor
Cross-Thread Operation Not Valid
Stataskscheduler and Sta Thread Message Pumping
How to Split a String with a String Delimiter
Draw Semi Transparent Overlay Image All Over the Windows Form Having Some Controls
C# Execute a Terminal Command in Linux
How to Assign a Base Class Object to a Derived Class Reference with an Explicit Typecast
In a "Using" Block Is a SQLconnection Closed on Return or Exception
"The Controls Collection Cannot Be Modified Because the Control Contains Code Blocks"
Intersection of Multiple Lists with Ienumerable.Intersect()
Assigning Out/Ref Parameters in Moq
How to Represent 0.1 in Floating Point Arithmetic and Decimal