gpt4 book ai didi

c# - 旋转数组集合

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:55 27 4
gpt4 key购买 nike

基本上,我有一个对象集合,每个对象都实现了 IValueCollection 类型的一个成员。

public interface IValueCollection : IEnumerable<decimal>
{
decimal this[int index] { get; set; }
}

MeasurementCollection.Values 属于 IValueCollection 类型。

根据下面的逻辑,我想旋转一个 IValueCollection 的集合,并在下面编写了扩展方法。

public static IEnumerable<IValueCollection> PivotValues(this MeasurementCollection items)
{
if(items.IsQuantized())
{
int s = (int)items.First().Template.Frequency;
int c = items.Count;
for (int n = 0; n < s; n++)
{
IValueCollection v = new MeasurementValueCollection(c);
for (int m = 0; m < c; m++)
v[m] = items.ElementAt(m).Values[n];
yield return v;
}
}
}

应该做的{{1,2,3}{4,5,6}{7,8,9}} 结果为 {{1,4,7},{2,5,8 },{3,6,9}}但是我认为有一些更好,更 slim 和更具可读性的表达方式可以做到这一点有人能指出我正确的方向吗?

编辑关于底层类的信息

interface IValueCollection : IEnumerable<decimal>
class MeasurementCollection : ICollection<IMeasurement>

interface IMeasurement
{
IMeasurementTemplate Template { get; }
......
}

interface IMeasurementTemplate
{
.....
MeasurementFrequency Frequency { get; }
}

最佳答案

我个人会强制提前评估您的集合,并将其用作数组。现在,每次你调用ElementAt ,您将评估 IEnumerable<T>再次导致大量重复搜索。

通过强制它预先评估数组,您可以简化整个过程。像这样的东西:

public static IEnumerable<IValueCollection> PivotValues(this MeasurementCollection items)
{
if(items.IsQuantized())
{
int elementLength = (int)items.First().Template.Frequency;
var itemArray = items.ToArray();
for (int n = 0; n < itemArray.Length; n++)
{
IValueCollection v = new MeasurementValueCollection(elementLength);
for (int m = 0; m < elementLength; m++)
{
v[m] = itemArray[m].Values[n];
}
yield return v;
}
}
else
yield break; // Handle the case where IsQuantized() returns false...
}

如果你控制MeasurementValueCollection ,我会添加一个构造函数,它接受 IEnumerable<decimal>作为输入,也。然后你可以这样做:

public static IEnumerable<IValueCollection> PivotValues(this MeasurementCollection items)
{
if(items.IsQuantized())
{
var elements = Enumerable.Range(0, (int)items.First().Template.Frequency);
var itemArray = items.ToArray();

foreach(var element in elements)
yield return new MeasurementValueCollection(
itemArray.Select(
(item,index) => itemArray[index].Value[element]
)
);
}
else
yield break; // Handle the case where IsQuantized() returns false...
}

关于c# - 旋转数组集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com