基本C#列表 - 添加未知数量的项目

时间:2015-10-16 04:56:41

标签: c#

我正在教自己C#和现代Windows编程,并且对C#中的列表有疑问,我还没有找到答案。我正在使用的参考书似乎表明,在您将变量分配给列表之前,在C#中,您需要为列表中的每个项目定义一个新变量并为其赋值。

我正在尝试编写一个简单的程序,让我可以编写文本注释,为其分配关键字,然后根据我选择的关键字过滤生成的注释组。根据我的判断,List似乎是C#中最好的机制,因为会有未知数量的音符。但是,我正在努力提前定义一个未知数量的变量名来存储笔记,以便添加到List中。

我是否在为C#查看错误的构造,误解了将变量值赋给List所需的内容,或者缺乏自动创建变量和变量名称的某种机制的知识,这些变量和变量名称可以作为清单?还有别的吗?

很抱歉,对于SE人群来说,这个问题太简单了,但这似乎是最好的问题。

2 个答案:

答案 0 :(得分:1)

我不确定你到底有什么困惑。但听起来你在构建类或使用C#类型时遇到了问题。为了保持现在的简单,你可以这样做。

// This represents individual note
public class Note 
{
    // Initialize keywords list in constructor
    // in order to avoid Null reference exception.
    public Note() {
        Keywords = new List<string>();
    }

    public string Title { get; set; }
    public string Content { get; set; }
    public List<string> Keywords { get; set; }
}

// In main code, you can simply have List<Note> to hold collection of any no of notes.
// Also, when user adds a note you will create a new Note instance and add to collection.
List<Note> notes = new List<Note>();

Note newNote = new Note();
newNote.Title = "Note 1";
newNote.Content = "Note 1 Content";
newNote.Keywords.Add("Test1");

notes.Add(newNote);

答案 1 :(得分:1)

List<T>是一种数据结构,允许您存储未知数量的T,但您不需要列表元素的变量名称 - 仅用于列表本身。

这是你需要的吗?

var notes = new List<string>()
{
    "This is a note.",
    "I am happy",
};

notes.Add("This is another happy note");

notes.AddRange(new [] { "Another happy notes", "This is also a note", });

var selected = notes.Where(n => n.Contains("happy")).ToList();

selected中的值为:

  

“我很开心”,“这是另一个快乐的音符”,“另一个快乐的音符”

相关问题