【问题标题】:C# Trying to swap one element in a list but ending up swapping them allC#试图交换列表中的一个元素,但最终将它们全部交换
【发布时间】:2021-06-02 16:55:19
【问题描述】:

我制作了一个 Matrix 对象,如下所示:

using System;
using System.Collections.Generic;

public class Matrix
{
  public List<List<float>> rows = new List<List<float>>();

  public Matrix()
  {

  }

  public Matrix(List<List<float>> Rows)
  {
    rows = Rows;
  }

并尝试定义一个函数,矩阵乘法。但是,当我尝试访问矩阵中的元素 (i,j) 并交换它时,它会交换该列中的每个元素吗?

public static Matrix operator*(Matrix A, Matrix B)
    {
      List<List<float>> input = new List<List<float>>();
      List<float> input_list = new List<float>();

      for(int i = 0; i < B.rows.Count; i++)
      {
        input_list.Add(0);
      }

      for(int i = 0; i < A.rows.Count; i++)
      {
        input.Add(input_list);
      }

      Matrix C = new Matrix(input);

      Console.WriteLine(C);
      // output
      // |0 0 0|
      // |0 0 0|
      // |0 0 0|
      C.rows[0][0] = 69;
      // output
      // |69 0 0|
      // |69 0 0|
      // |69 0 0| ???          
      Console.WriteLine(C);
      return C;

我希望 C.rows[0][0] = 69;导致输出 |69 0 0| |0 0 0| |0 0 0|

【问题讨论】:

  • Listreference typeinput.Add(input_list); 多次添加同一个实例 input_list。显然你想要input.Add(new List&lt;float&gt;());,但首先列出列表并不是represent a matrix 的好方法。

标签: c# list


【解决方案1】:

input.Add(input_list); 替换为input.Add(input_list.ToList());,因为您需要不同的列表实例。

不过,这是一种绝对可怕的构建矩阵的方法。您正在采用所有计算机科学中最优化的数据结构之一,并试图将其拼凑起来,以摆脱困境和希望。尤其糟糕,因为 .Net 有经过大量优化和矢量化的 a built-in matrix class

【讨论】:

    【解决方案2】:

    这是因为您正在添加对象引用。 使用 System.Linq;

     for(int i = 0; i < A.rows.Count; i++)
     {
        input.Add(input_list.Select(item => (T)item.Clone()).ToList());
     }
    

    【讨论】:

    • 这可行,但 Blindy 的答案更好,代码更少
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多