-
May 11th, 2010, 05:16 AM
#1
[RESOLVED] Skip certain elements in an array?
Elements cannot be removed from an array. Is it possible to skip or hide particular items in an array by stating the element ID of the elements desired to be skipped? As far as I understand the method Skip() only skips the first element or elements, depending on how many you specified. Here is an example below of why I need to skip certain elements in the array:
Code:
public void MergeVolumes()
{
Volumes[] lVolumes = mWebService.getAllVolumes();
List<string> contents = new List<string>();
int count = lVolumes.Length; // Original value of count
int volumeOrder = 1; // First category of unknown number of categories
int ID = 0; // Element ID
// Add the content of all volumes of a book to a list<string> "contents" in chronological order
for (int i = 0; i < count; i++)
{
int volumeNo = lVolumes[ID].Number;
if (volumeNo == volumeOrder)
{
// Add content of the current volume to the list
contents.Add(lVolumes[ID].Content);
// Skip this element each time
lVolumes.Skip(ID); // PROBLEM!
// Look for next volume now
volumeOrder++;
}
else
{
// Keep looping till find the desired volume
count++;
}
// Once run through array once, rerun
if (ID == lVolumes.Length - 1)
{
// Reset to zero
ID = 0;
}
ID++;
}
}
I have considered using some form of two-dimensional arraylist,containing both the volume no and the volume content, enabling me to remove specified elements from the arraylist but I don't know what I can use....
-
May 11th, 2010, 01:41 PM
#2
Re: Skip certain elements in an array?
Two fast approaches:
1. Use List instead of Array.
2. Have another temporary Array - copy all needed (those should be kept) elements into this temporary Array. Then erase all items from original array, and copy the temporary array into main array.
-
May 12th, 2010, 11:06 PM
#3
Re: Skip certain elements in an array?
Another option maybe to use LINQ to select just the items in the collection that you wish to process. Then iterate over the collection returned by the LINQ query, rather than the original collection. Note though that they are still in effect the 'same' collection. So you will find that similar restrictions apply when it comes to updating/deleting items from the LINQ collection.
Also, if possible, do what Ajay says in '1...'
Rob
-
Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......
-
May 12th, 2010, 11:52 PM
#4
Re: Skip certain elements in an array?
You defiantly want to be using List<> instead of an array... almost always.
You can use members like List.ForEach and List.FindAll, which is easy using lambdas.
-
May 17th, 2010, 09:58 AM
#5
Re: Skip certain elements in an array?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|