显示索引 C# 中的子列表值

Show sublist value from index C#

我的问题是我有 M 个子问题。每个子问题包括 x(双数组)和降低的成本,其在每次迭代 m 时具有不同的值。我想显示 x 在所有子问题中具有最小的降低成本。这是我的 class:

public class Subproblem
{
    public double[,] x { get; set; }
    public double ReducedCost { get; set; }
}

至此,我已经可以得到最小的Reduced Cost和它的指标。现在我想显示该索引上的 x 值(双数组)。我有这样的代码:

var sub = new List<Subproblem>();
for (int m = 0; m < M; ++m)
{
Subproblem s = new Subproblem();
s.x = new double[DC1, DC1];      
s.ReducedCost = model.ObjVal;
    for (int i = 0; i < DC1; ++i)
    {
        for (int j = 0; j < DC1; ++j)
        {
            s.x[i, j] = x[i, j].X;
        }
    }
    sub.Add(s);
}
double minRC = sub.Min(a => a.ReducedCost);
int minRCIndex = sub.FindIndex((i) => i.ReducedCost == minRC);
Console.WriteLine(sub.x(minRCIndex));

最后一行(Console.WriteLine(sub.x(minRCIndex));)还是红色下划线,不知道怎么写

应该是

var objWithMinReduceCost = sub[minRCIndex];
//Now you have the object of Subproblem derived from your logic.
//You can access x property of it have further logic to process it.
for (int i = 0; i < DC1; ++i)
{
    for (int j = 0; j < DC1; ++j)
    {
         Console.WriteLine(objWithMinReduceCost.x[i, j]);
    }
}

如果您只是想获得最小的降低成本的子问题,您应该这样做:

Subproblem minimumReducedCostedSubproblem = sub[minRCIndex];

你可以像这样打印矩阵:

for (int i = 0; i < DC1; ++i)
{
    for (int j = 0; j < DC1; ++j)
    {
        Console.Write(minimumReducedCostedSubproblem.x[i, j] + "\t");
    }
    Console.Write("\n");
}

但你似乎有点困惑。您正在将具有相同对象的子问题推入 sub 列表 M 次。因为 model.ObjVal 在第一个 for 循环中没有改变。那里也发生了一些奇怪的事情。

如果您有兴趣获取 double 数组,您可以这样做:

double[,] result = sub.First(i => i.ReducedCost == minRC).x;

尽管如 Tolga 所述,您的所有元素都将与您当前的代码具有相同的 ReducedCost