插入重复值linq [英] Insert duplicates values linq
本文介绍了插入重复值linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在值的集合中
[0, 2, 25, 30]
我正在尝试使用linq
I'm trying to do with linq
[0, 0, 0, 2, 2, 2, 25, 25, 25, 30, 30, 30] //Replicate 2 times (values repeated 3 times)
有什么办法可以使用linq吗?
Is there someway to do it with linq?
推荐答案
使用值类型很容易,只需使用Enumerable.Repeat
:
With value types it's easy, just use Enumerable.Repeat
:
var result = collection.SelectMany(x => Enumerable.Repeat(x, 3));
如果是数组,则使用ToArray
;如果它是列表,则在末尾使用ToList
.
If it was an array use ToArray
if it was a list use ToList
at the end.
对于引用类型,这取决于您是否确实想要相同的引用,然后还可以使用Repeat
.否则,您需要创建实例的深层克隆",例如通过使用
With reference types it depends if you really want the same reference, then you can also use Repeat
. Otherwise you need to create "deep-clones" of the instance, for example by using a copy constructor if available:
var result = collection
.SelectMany(x => Enumerable.Range(1, 3).Select(i => new YourType(x)));
这篇关于插入重复值linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文