Reputation: 7792
Hey all. Is there a way to copy only a portion of a single (or better yet, a two) dimensional list of strings into a new temporary list of strings?
Upvotes: 16
Views: 22793
Reputation: 55750
I'm not sure I get the question, but I would look at the Array.Copy function (if by lists of strings you're referring to arrays)
Here is an example using C# in the .NET 2.0 Framework:
String[] listOfStrings = new String[7]
{"abc","def","ghi","jkl","mno","pqr","stu"};
String[] newListOfStrings = new String[3];
// copy the three strings starting with "ghi"
Array.Copy(listOfStrings, 2, newListOfStrings, 0, 3);
// newListOfStrings will now contains {"ghi","jkl","mno"}
Upvotes: 1
Reputation: 9698
FindAll will let you write a Predicate to determine which strings to copy:
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
List<string> copyList = list.FindAll(
s => s.Length >= 5
);
copyList.ForEach(s => Console.WriteLine(s));
This prints out "three", because it is 5 or more characters long. The others are ignored.
Upvotes: -1
Reputation: 1502276
Even though LINQ does make this easy and more general than just lists (using Skip
and Take
), List<T>
has the GetRange
method which makes it a breeze:
List<string> newList = oldList.GetRange(index, count);
(Where index
is the index of the first element to copy, and count
is how many items to copy.)
When you say "two dimensional list of strings" - do you mean an array? If so, do you mean a jagged array (string[][]
) or a rectangular array (string[,]
)?
Upvotes: 40