我有一个对象“Compact”,它由一个ID和两个数组组成:
public class Compact
{
public int Id { get; set; }
public int[] Number { get; set; }
public double[] Value { get; set; }
public Compact(int id, int[] number, double[] value)
{
Id = id;
Number = number;
Value = value;
}
}
Compact对象的列表可以按如下方式初始化:
List<Compact> c = new List<Compact>
{
new Compact(1, new int[] { 1, 2, 3 }, new double[] { 0.05, 0.02, 0.03 }),
new Compact(2, new int[] { 1, 2, 3 }, new double[] { 0.07, 0.01, 0.04 }),
new Compact(3, new int[] { 1, 2, 3 }, new double[] { 0.02, 0.025, 0.05 })
};
我正在寻找一种优雅的方法将此对象展平为对象“Flattened”:
public class Flattened
{
public int Id { get; set; }
public int Number { get; set; }
public double Value { get; set; }
public Flattened(int id, int number, double value)
{
Id = id;
Number = number;
Value = value;
}
}
展平的结果将对应于:
List<Flattened> f = new List<Flattened>
{
new Flattened(1,1,0.05),
new Flattened(1,2,0.02),
new Flattened(1,3,0.03),
new Flattened(2,1,0.07),
new Flattened(2,2,0.01),
new Flattened(2,3,0.04),
new Flattened(3,1,0.02),
new Flattened(3,2,0.025),
new Flattened(3,3,0.05)
};
我可以使用循环进行扁平化,但是我想知道是否有更适合性能的方法,比如Linq操作或不同的集合类型?
3条答案
按热度按时间gwo2fgha1#
您可以简单地运行
for
循环。注意我假设两个数组的项数相同。
osh3o9ms2#
使用LINQ,您可以
SelectMany
执行扁平化,Zip
,顾名思义,将Number
和Value
数组“压缩”在一起,并将函数(n, v) => new Flattened(x.Id, n, v)
应用于每对数组,从每对数组创建一个Flattened
对象。1rhkuytd3#
您可以使用Linq来实现这一点,
SelectMany
和Zip
的组合应该可以实现这一点(n, v) => (n, v)
创建Number
和Value
对的元组dotnetfiddle