我正在尝试遍历一系列参数并按照它们循环的顺序将它们与另一参数相关联(该类的类型为付款,其属性为 SupplementalPayment 也是付款类型)。 因此,通过4次付款,付款4将与付款3相关联,付款3将与付款2相关联,依此类推。
我无法通过无限量的参数来实现这一目标。
这就是我现在所使用的方法:
private Payment SortPayments(params Payment[] payments)
{
Payment parentPayment, lastPayment;
lastPayment = parentPayment = null;
foreach (Payment currentPayment in payments)
{
if (currentPayment != null)
{
lastPayment = currentPayment;
if (parentPayment == null)
{
parentPayment = lastPayment;
}
else if(parentPayment.SupplementalPayment == null)
{
parentPayment.SupplementalPayment = lastPayment;
}
else if (parentPayment.SupplementalPayment.SupplementalPayment == null)
{
parentPayment.SupplementalPayment = lastPayment;
}
else if (parentPayment.SupplementalPayment.SupplementalPayment.SupplementalPayment == null)
{
parentPayment.SupplementalPayment.SupplementalPayment.SupplementalPayment = lastPayment;
}
}
}
return parentPayment;
}
正如您所看到的,它不是动态的,最多只能进行四次补充支付。任何人都知道该怎么做?
答案 0 :(得分:2)
也许我根本不理解您的问题,但您只是想将每笔付款与下一笔付款相关联。在这种情况下,一个简单的for循环就足够了:
private Payment SortPayments(params Payment[] payments)
{
if(payments.Length == 0) return null;
for(int i = 0; i < payments.Length - 1; i++)
payments[i].SupplementalPayment = payments[i + 1]
return payments[0];
}
答案 1 :(得分:1)
答案 2 :(得分:1)
也许你可以使用循环来做这样的事情:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Payments
{
class Program
{
static void Main(string[] args)
{
Payment p1 = new Payment();
Payment p2 = new Payment();
Payment p3 = new Payment();
Payment Sorted = SortPayments(p1, p2, p3);
}
static private Payment SortPayments(params Payment[] payments)
{
if(payments.Length == 0)
{
return null;
}
Payment FirstPayment = payments[0];
Payment current = FirstPayment;
for (int i = 1; i < payments.Length; i++ )
{
current.SupplementalPayment = payments[i];
current = current.SupplementalPayment;
}
return FirstPayment;
}
}
}
答案 3 :(得分:0)
如何做到这一点有无限的方法。 首先出现在我的脑海中(可能不是最佳的)是递归和堆栈的活动参数。 只需将数据整理到列表列表中即可。递归函数“visit”循环遍历一个列表,将元素推送到堆栈并调用visit访问下一个列表,直到没有要访问的列表。最后,你有相关元素的堆栈。
重复调用后,您将从堆栈中弹出。 这需要抛光,但你明白了。
答案 4 :(得分:0)
感谢您的反馈。这就是我最终的结果。 唯一的区别在于答案是因为输入的一些参数是空的。
private Payment SortPayments(params Payment[] payments)
{
for (int i = 0; i < payments.Length - 1; i++)
{
if (payments[i + 1] != null)
{
payments[i].SupplementalPayment = payments[i + 1];
}
else
{
int j = 1;
while (true)
{
if (payments[i + j] == null)
{
j++;
}
else
{
payments[i].SupplementalPayment = payments[i + j];
i += j;
}
}
}
}
return payments[0];
}