INTRO:一段时间以来一直在寻找这个答案,尽管进行了多次搜索,却没有在档案中找到答案。问题太简单了,或者做了些什么来违反C#
的规律我是双重链接列表的新手,他们正在努力!
我在获取双向链表以从列表中的对象中吐出变量时遇到问题。
我已经尝试在新文件中简化问题,以便在脑海中解决这个问题,但我无法找到正确的语法来在DLL中的对象中查找变量。
我已将其分解为DLL中的五个对象,每个对象都有一个标题。 现在我想找一个对象并返回它的标题。 但相反:aaaaaaaaaaaaaaaaaaarrgh!我到底做错了什么?
namespace ADS
{
public partial class DLL_Generic_Object : Form
{
public DLL_Generic_Object()
{
InitializeComponent();
}
//create class
public partial class Weapon
{
string Title;
public Weapon(string title)
{
this.Title = title;
}
}
//create objects;
Weapon object1 = new Weapon("Revolver");
Weapon object2 = new Weapon("Candlestick");
Weapon object3 = new Weapon("Lead Pipe");
Weapon object4 = new Weapon("Rope");
Weapon object5 = new Weapon("Knife");
public class Structures
{
public string getTitle(LinkedList<Object> nameofDLL)
{
string gotTitle = "How do I Find the Title variable of an Object in the DLL?";
return gotTitle;
}
}
//create an object Doubly Linked List
LinkedList<object> weapons = new LinkedList<object>();
private void btnExecute_Click(object sender, EventArgs e)
{
PrintNodes(weapons); //This will show the DLL is empty.
//Add nodes to the list
weapons.AddFirst(object1); //add a node to the front of the list
//Add a node after a specific node.
weapons.AddAfter(weapons.Find(object1), object2);
weapons.AddAfter(weapons.Find(object2), object4);
//Add a node before a specific node.
weapons.AddBefore(weapons.Find(object4), object3);
//Add a node to the end of the list
weapons.AddLast(object5);
PrintNodes(weapons); // This will show the DLL has 5 Nodes.
// Find the value of a node
}
public string FindTitle(LinkedList<Object> nameofDLL)
{
// initialise a Structures class
Structures structure = new Structures();
// Find the value of a node
string value = structure.getTitle(weapons) + "\r\n";
return value;
}
public void PrintNodes(LinkedList<object> values)
{
if (values.Count != 0) //check if there are any nodes in the list
{
txtOutput.Text += "The number of nodes is: " + values.Count.ToString() + "\r\n";
txtOutput.Text += FindTitle(weapons);
}
else
txtOutput.Text += "The Doubly Linked List is empty" + "\r\n";
}
}
}
答案 0 :(得分:0)
您似乎从错误的角度接近问题。不建议尝试将元素放在双链表的特定索引处,因为这不是它的设计目的。使用DLL的目的是拥有一个集合,可以使用列表中的元素而不是列表本身来导航。例如,如果从某个源获取给定节点,则可以使用Next
和Previous
属性来导航列表。
如果目标是遍历整个列表,则有两种常规方法可以执行此操作。第一个也是最直接的是foreach
方法:
foreach (var node in linkedList)
{
Console.WriteLine(node.Title);
}
第二种方法是使用while
。这种方法稍微复杂一些,但它更清楚地证明了LinkedList的行为和意图:
var node = linkedList.First;
while (node != null)
{
Console.WriteLine(node.Value.Title);
node = node.Next;
}
如果你绝对需要来获取特定索引的元素,那么这是可能的,最简单的方法是使用ElementAt
或ElementAtOrDefault
LINQ方法。它们之间的区别在于,如果给定索引超出列表的边界,ElementAt
将抛出异常,而ElementAtOrDefault
将返回给定类型的默认值(在您的{的情况下) {1}}类型,默认值为Weapon
) - 您应该选择哪种方法取决于您对特定实现的偏好行为:
null
但正如我在评论中所说,上述方法基本上将LinkedList视为常规列表,因此如果您需要经常这样做,那么您需要问问自己为什么您不仅仅使用List。 / p>