更改对象数组中的项目

问题描述 投票:0回答:1

如何更改数组中两个对象的位置?当我尝试这样做时,在我看来,它们是对 table1 和 table2 变量中的对象的引用。

                            List<Table> tableList = new List<Table>();

                            Table tabl = new Table();
                            tabl.HexToInt = 1;
                            tabl.Data = "a";
                            tableList.Add(tabl);

                            tabl = new Table();
                            tabl.HexToInt = 2;
                            tabl.Data = "b";
                            tableList.Add(tabl);

                            tabl = new Table();
                            tabl.HexToInt = 3;
                            tabl.Data = "c";
                            tableList.Add(tabl);

                            List<string> letter = tableList.Select(x => x.Data).ToList();

                            Table table1 = tableList[letter.IndexOf("a")];
                            Table table2 = tableList[letter.IndexOf("c")];

                            tableList[tableList.IndexOf(table1)] = table2;
                            tableList[tableList.IndexOf(table2)] = table1;
c# list reference
1个回答
0
投票

要在 C# 中交换列表中两个对象的位置,您需要确保正确处理引用,尤其是当对象看起来像代码中那样切换两次时。这是交换列表中两个项目的简化且正确的方法:

List<Table> tableList = new List<Table>();

// Add tables
tableList.Add(new Table { HexToInt = 1, Data = "a" });
tableList.Add(new Table { HexToInt = 2, Data = "b" });
tableList.Add(new Table { HexToInt = 3, Data = "c" });

// Find indexes
int indexA = tableList.FindIndex(t => t.Data == "a");
int indexC = tableList.FindIndex(t => t.Data == "c");

// Swap using a temporary variable
Table temp = tableList[indexA];
tableList[indexA] = tableList[indexC];
tableList[indexC] = temp;

此代码根据数据查找要交换的项目的位置,然后使用临时变量来帮助正确交换它们在列表中的位置。

© www.soinside.com 2019 - 2024. All rights reserved.