tags:

views:

75

answers:

3

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?

+1  A: 

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[,])?

Jon Skeet
A: 

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 3 of the strings stargin with "ghi"
Array.Copy(listOfStrings, 2, newListOfStrings, 0, 3);

// newListOfStrings will now contain {"ghi","jkl","mno"}
Miky Dinescu
A: 

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.

Dave Bauman