linq 数组的拼合对象

kx5bkwkv  于 2023-01-22  发布在  其他
关注(0)|答案(3)|浏览(127)

我有一个对象“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操作或不同的集合类型?

gwo2fgha

gwo2fgha1#

您可以简单地运行for循环。

List<Compact> ls = 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 })
};
List<Flattened> ls2 = new List<Flattened>();
foreach (Compact compact in ls)
{
    for (var index = 0; index < compact.Number.Length; index++)
    {
        ls2.Add(new Flattened(compact.Id, compact.Number[index], compact.Value[index]));
    }
}

注意我假设两个数组的项数相同。

osh3o9ms

osh3o9ms2#

使用LINQ,您可以

c.SelectMany(
    x => x.Number.Zip(x.Value, (n, v) => new Flattened(x.Id, n, v))
).ToList()

SelectMany执行扁平化,Zip,顾名思义,将NumberValue数组“压缩”在一起,并将函数(n, v) => new Flattened(x.Id, n, v)应用于每对数组,从每对数组创建一个Flattened对象。

1rhkuytd

1rhkuytd3#

您可以使用Linq来实现这一点,SelectManyZip的组合应该可以实现这一点
(n, v) => (n, v)创建NumberValue对的元组

List<Compact> ls = 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 })
};

var flattened = ls
    .SelectMany(
        c => c.Number.Zip(c.Value, (n, v) => (n, v)),
        (c, nv) => new Flattened(c.Id, nv.n, nv.v)
    ).ToList();

dotnetfiddle

相关问题