C# 将列表的一部分复制到新列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/926771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copying a portion of a list to a new list
提问by bitcycle
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?
大家好。有没有办法只将单维(或者更好,二维)字符串列表的一部分复制到新的临时字符串列表中?
采纳答案by Jon Skeet
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:
尽管 LINQ 确实使这变得更简单,而且比仅使用列表(使用Skip
和Take
)更通用,但List<T>
它的GetRange
方法使它变得轻而易举:
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.)
(哪里index
是要复制的第一个元素的索引,以及count
要复制的项目数。)
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[,]
)?
当您说“二维字符串列表”时-您的意思是数组吗?如果是这样,您是指锯齿状阵列 ( string[][]
) 还是矩形阵列 ( string[,]
)?
回答by Mike Dinescu
I'm not sure I get the question, but I would look at the Array.Copyfunction (if by lists of strings you're referring to arrays)
我不确定我是否明白这个问题,但我会查看Array.Copy函数(如果通过字符串列表您指的是数组)
Here is an example using C# in the .NET 2.0 Framework:
以下是在 .NET 2.0 框架中使用 C# 的示例:
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"}
回答by Dave Bauman
FindAll will let you write a Predicate to determine which strings to copy:
FindAll 将让您编写一个 Predicate 来确定要复制的字符串:
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.
这将打印出“三个”,因为它有 5 个或更多字符长。其他的被忽略。