[英]An efficient way to merge / copy array index-wise in C#
我在 WPF 项目中工作,我需要使用计时器将图像显示为广告。 图像以下列方式以数组形式给出。
array1 = { img1, img2, img3 }
array2 = { img4, img5, img6, img7 }
array3 = { img8, img9 }
我需要按以下方式显示图像(按索引合并/复制数组):
finalarray = { img1, img4, img8, img2, img5, img9, img3, img6, img7}
数组的大小可以是 0 到 20。我尝试使用 for/while 循环,结果代码变得不必要地长了。 我需要一种简单有效的方法来实现这一点。
任何建议在这里表示赞赏。 提前致谢。
我不知道您是否提供了正确的解决方案。
但请检查:-
string[] array1 = new string[] { "img1", "img2", "img3" };
string[] array2 = new string[] { "img4", "img5", "img6", "img7" };
string[] array3 = new string[] { "img8", "img9" };
List<string> arrayList = new List<string>();
for (int i = 0; i < 20; i++)
{
if (array1.Length > i)
arrayList.Add(array1[i]);
if (array2.Length > i)
arrayList.Add(array2[i]);
if (array3.Length > i)
arrayList.Add(array3[i]);
}
//您现在可以打印 arrayList。
//它将返回:- { img1, img4, img8, img2, img5, img9, img3, img6, img7}
如果 arrays 的数量不固定,您可以再创建一个 class,此解决方案应该适合您:
class Program
{
public class Image
{
public string Name { get; set; }
public Image(string name)
{
Name = name;
}
}
public class ImageWithIndex : Image
{
public ImageWithIndex (string name, int index) : base(name)
{
Index = index;
}
public int Index { get; set; }
}
static void Main(string[] args)
{
var images = new List<List<Image>>
{
new List<Image> { new Image("1"), new Image("2"), new Image("3") },
new List<Image> { new Image("4"), new Image("5"), new Image("6"), new Image("7") },
new List<Image> { new Image("8"), new Image("9") }
};
var sortedList = images
.SelectMany(innerList => innerList.Select((image, index) => new ImageWithIndex(image.Name, index)))
.OrderBy(i => i.Index)
.Select(i => i as Image);
}
}
我喜欢创建一个 arrays 数组(锯齿状数组)并循环遍历直到没有更多内容可添加到结果图像列表的想法。 下面的代码适用于任意数量的 arrays 以及任意数量的图像。
static void Main(string[] args)
{
var images = GetImages(
new Image[] { img1, img2, img3 },
new Image[] { img4, img5, img6, img7 },
new Image[] { img8, img9 });
}
static Image[] GetImages(params Image[][] ads)
{
var list = new List<Image>();
int index = 0;
bool done;
do
{
done = true;
for (int i = 0; i < ads.Length; i++)
{
if (index<ads[i].Length)
{
list.Add(ads[i][index]);
done = false;
}
}
index++;
} while (!done);
return list.ToArray();
}
在使用字符串而不是图像进行测试时显示结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.