【发布时间】:2020-04-15 14:39:21
【问题描述】:
我遇到了一个问题,如果我从字符串列表中“获取”,它会引用这些值,所以当我从原始列表中删除它们时,它们也会从我的“获取列表”中删除”。有没有办法从列表中获取值而不是引用?请参阅下面的代码。
// ids is a list of strings, use example: ["123","456","789"]
var chunkIds = ids.Take(10);
// right here, chunkIds = ["123","456","789"]
ids.RemoveRange(0, ids.Count < 10? ids.Count : 10);
// after remove the elements we just took from the original list, chunkIds = []
// I want chunkIds to be ["123","456","789"], and ids should be []
我在文档中没有看到任何方法(或者我是盲人): https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take?view=netframework-4.8
【问题讨论】:
-
添加
ToList()。 Take是懒惰的。 -
@Caramiriel OMG *面对双手*。这绝对有效。如果您想将其添加为答案,我会接受。
-
这能回答你的问题吗? IEnumerable Where() and ToList() - What do they really do? - 我将它标记为重复,不完全相同,因为它使用
Where而不是Take,但结果是相同的。不过我花了一段时间才找到一个好的副本。