列表/iEnumerable中的重复数字



我有一个列表,例如

List<int> List1 = new List<int>{1, 5, 8, 3, 9};

重复列表中元素以获得{1、1、5、5、8、8、3、3、9、9、9}?

的简单方法是什么。

我需要的原因是我要绘制列表中的元素,并且需要制作"步骤图"。

var list2 = List1.SelectMany(x => new []{x, x}).ToList();

i将创建(扩展)方法,该方法列举源并产生所需次数的每个项目:

public static IEnumerable<T> RepeatItems<T>(this IEnumeable<T> source, int count)
{
    foreach(var item in source)
       for(int i = 0; i < count; i++)
          yield return item;
}

因此,您将避免创建大量数组。用法:

var result = List1.RepeatItems(2).ToList();

如果您只需要复制项目,则解决方案更简单:

public static IEnumerable<T> DuplicateItems<T>(this IEnumeable<T> source)
{
    foreach(var item in source)
    {
        yield return item;
        yield return item;
    }
}

副本的用法扩展:

var result = List1.DuplicateItems().ToList();

另外,如果您只列举结果,则无需将其转换为列表。如果您不从结果中修改(添加/删除)项目,则将其转换为数组更有效。

从上面的评论中获取

var sequence2 = List1.SelectMany(x => Enumerable.Repeat(x, 2));

是一个更好的解决方案,因为它可以避免毫无意义的内存分配。更改为n重复会变得更简单,在此重复方面,开销的变化将变得更加重要。

这是您正在尝试减少内存分配:

// Pre-allocate the space to save time
List<int> dups = new List(List1.Count * 2);
// Avoid allocating an enumerator (hopefully!)
for(int i=0; i<List1.Count; i++)
{
  var value = List1[i];
  dups.Add(value);
  dups.Add(value);
}

不是Linq,但它是内存有效

最新更新