从c#中的列表中删除
我有一个 wpf c# 应用程序,它将任务从文本文件加载到树视图,有关任务的数据正在加载到列表中,我试图删除列表中位置 I 的数据,但我不知道如何删除。我有这个 for 循环检查,以查看所选的 treeView 项目是否等于列表中位置 I 的项目,如果是,我想从列表中删除该项目。这是有效的 for 循环,我只是想知道如何进行实际删除,我尝试过在 msdna 上找到的诸如 .delete
和 .remove
之类的东西。
for (int i = 0; i < name.Count; ++i)
{
string selectName = ((TreeViewItem)(treeView1.SelectedItem)).Header.ToString();
if (selectName == name[i])
{
//name.Remove(i) or name.Remove[i] or name[i].Remove
}
}
I have a wpf c# application, that loads tasks to a treeView from a text file, the data about the tasks are loading into a list, Im trying to delete data in position I in the list, but i can not figure out how. I have this for loop checking to see if the selected treeView item is equal to the item in position I in the list and if so I wanna delete that item from the list. Here is the for loop which works, im just wondering how to do the actual delete, I've tried things such as .delete
and .remove
which I found on msdna.
for (int i = 0; i < name.Count; ++i)
{
string selectName = ((TreeViewItem)(treeView1.SelectedItem)).Header.ToString();
if (selectName == name[i])
{
//name.Remove(i) or name.Remove[i] or name[i].Remove
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 name 是一个
List
那么你可能需要name.RemoveAt(i)
如果我正确理解了这个问题。或者,您可以只使用
name.RemoveAll(n => n == selectName);
而不是 for 循环。If name is a
List<T>
then you probably wantname.RemoveAt(i)
if I understand the question correctly.Alternatively, you could just use
name.RemoveAll(n => n == selectName);
instead of the for loop.怎么样:
How about:
您必须为 List.Remove() 提供一个对象,而不是索引。
所以,假设名称是一个列表,
You have to give List.Remove() an object, not an index.
So, assuming name is a List,
根据您的应用程序需求,您的数据结构应该具有一定的父子关系。您所要做的就是删除从父级中选择的
Child
,并且WPF
中的TreeView
应该会自动更新。我建议您阅读 Josh Smith 的有关使用
ViewModels
和的文章>TreeView
以便于管理。相信我,您越早开始使用更强大的数据结构,您的生活就会变得更加轻松,只需记住TreeView
仅代表提供的数据,您应该有其他方法来直接编辑数据而不是TreeView
。Depending on your application needs, your data structure should have some time of Parent-Child relationship. All you should have to do is remove the
Child
that is selected from the parent, and theTreeView
inWPF
should just automatically update.I suggest you read Josh Smith's article on using
ViewModels
with theTreeView
for easier management. Trust me it will make your life a lot easier the sooner you start using a stronger data structure, and just remember that aTreeView
only represents the data provided, and you should have other methods to edit the data directly and not theTreeView
.