【发布时间】:2013-02-01 03:56:30
【问题描述】:
有没有一种巧妙的方法可以使用 LINQ 将多个列表合并到一个列表中以有效地复制它?
public class RGB
{
public int Red { get; set; }
public int Green { get; set; }
public int Blue { get; set; }
public RGB(int red, int green, int blue) { Red = red; Green = green; Blue = blue; }
}
public void myFunction()
{
List<int> red = new List<int> { 0x00, 0x03, 0x06, 0x08, 0x09 };
List<int> green = new List<int> { 0x00, 0x05, 0x06, 0x07, 0x0a };
List<int> blue = new List<int> { 0x00, 0x02, 0x03, 0x05, 0x09 };
List<RGB> colors = new List<RGB>();
colors.Add(new RGB(red[0], green[0], blue[0]));
colors.Add(new RGB(red[1], green[1], blue[1]));
colors.Add(new RGB(red[2], green[2], blue[2]));
colors.Add(new RGB(red[3], green[3], blue[3]));
colors.Add(new RGB(red[4], green[4], blue[4]));
}
或者,由于列表是分开到达的,按如下顺序合并它们会更有效。
public class RGB
{
public int Red { get; set; }
public int Green { get; set; }
public int Blue { get; set; }
public RGB(int red, int green, int blue) { Red = red; Green = green; Blue = blue; }
}
public void myFunction()
{
List<int> red = new List<int> { 0x00, 0x03, 0x06, 0x08, 0x09 };
List<RGB> colors = new List<RGB>();
colors.Add(new RGB(red[0], 0, 0));
colors.Add(new RGB(red[1], 0, 0));
colors.Add(new RGB(red[2], 0, 0));
colors.Add(new RGB(red[3], 0, 0));
colors.Add(new RGB(red[4], 0, 0));
List<int> green = new List<int> { 0x00, 0x05, 0x06, 0x07, 0x0a };
colors[0].Green = green[0];
colors[1].Green = green[1];
colors[2].Green = green[2];
colors[3].Green = green[3];
colors[4].Green = green[4];
List<int> blue = new List<int> { 0x00, 0x02, 0x03, 0x05, 0x09 };
colors[0].Blue = blue[0];
colors[1].Blue = blue[1];
colors[2].Blue = blue[2];
colors[3].Blue = blue[3];
colors[4].Blue = blue[4];
}
【问题讨论】:
-
相似,但不同。前者专门针对内存性能和资源优化。这不是关于资源的问题,答案不是针对特定的性能指标,而是提供了广泛的可能性,不受性能因素的限制。
-
另一个问题写得不好,答案不如这里的好,但它根本不特别关心性能(OP刚刚提到他/她正在跑步内存不足),这是一个简单且最小的问题,而且它较旧,因此我将其视为“可能的”重复。无论哪种方式,其他人都应该知道存在类似的问题并具有指向它的链接。
标签: c# linq design-patterns