在 类 中展平数组的动态方法?

Dynamic way to flatten arrays in classes?

我正在遍历包含双精度数组的对象。名字变了。假设这是 Lab 样本的一个对象,我正在尝试获取 Sample 对象的平面表示。

发件人:

Sample
{
    public string Name
    public string Type
    ...
    public double[] RawReadings
}

例如:

Name,
RawRead1,
RawRead2,
RawRead3,
...
RawReadn

我如何找到 sample.RawReadings 给我数组中的所有 n 项? 我不在乎它是否被命名。

为清楚起见进行编辑:我希望结果列表中的每个项目都具有 Name 和与 class 中的属性一样多的双打,因为有 RawReads。我希望结果列表中的每个项目都有一个名称和一个数组 - 这将与我所拥有的相同。

示例 LinQ:

from sample in Samples
select new
{
    Name = sample.Name,
    sample.RawReadings
}

这可能吗?

编辑: 我正在将此提供给第 3 方 API 调用,该调用期待 "row and column format" 中的内容。 Aspose.Cells 准确地说是 ImportCustomObject。可以通过多次调用并手动对齐它们来解决它,但这可能很棘手且容易出错。

I want the each item in the resulting list to have the Name and as many doubles as there are RawReads.

您不能使用匿名类型来做到这一点。匿名类型在 编译时 中指定了 属性 名称和类型,而您希望在 执行时 中指定它们。目前尚不清楚您为什么要尝试这样做,但最接近的可能是使用动态类型,为此您可以使用 expando:

public dynamic SampleToDynamic(Sample sample)
{
    IDictionary<string, object> expando = new ExpandoObject();
    expando["Name"] = sample.Name;
    for (int i = 0; i < sample.RawReadings.Length; i++)
    {
        expando["RawRead" + (i + 1)] = sample.RawReadings[i];
    }
    return expando;
}

假设你有这样的样本数据(这里我将 RawReadings 表示为逗号分隔但实际上它们是双精度数组):-

Name     Type      RawReadings
--------------------------------
foo      bar         1.2, 3.5, 4.8
foo1     bar1        8.3, 6.6

据我所知,您需要获取所有 RawReadings 值作为具有名称和类型的新属性。但是正如@JonSkeet 已经解释的那样,这是不可能的。可能的是将 RawReadings 数据展平并将其与 Sample class 的其他属性组合,如下所示:-

Name     Type     RawReadings
--------------------------------
foo      bar       1.2
foo      bar       3.5
foo      bar       4.8
foo1     bar1      8.3
foo1     bar1      6.6

这里是代码:-

var result = sampleData
         .SelectMany(x => x.RawReadings, (sampleObj, rawObj) => new { sampleObj, rawObj })
         .Select(x => new
                     {
                          Name = x.sampleObj.Name,
                          Type = x.sampleObj.Type,
                          raws = x.rawObj
                      });

假设您有这样的数据,

var samples = new List<Sample>();
samples.Add(new Sample { Name = "A", Type = "TypeA", RawReadings = new double[] { 1.5, 2.5, 3.5 } });
samples.Add(new Sample { Name = "B", Type = "TypeB", RawReadings = new double[] { 1.6, 2.6, 3.6 } });

你想要这样的东西

A 1.5
A 2.5
A 3.5
B 1.6
B 2.6
C 3.6

您可以使用此代码

var sampleReadings = new List<KeyValuePair<string, double>>();
samples.ForEach(s => 
            s.RawReadings.ToList().ForEach(r => 
                                    sampleReadings.Add(new KeyValuePair<string, double>(s.Name, r))));