我什么时候应该在 C# 中使用数组列表(即 List<string []> = new List<string []>())?

When should I use List of Array (i.e. List<string []> = new List<string []>()) in C#?

上下文

我有两个用户输入字段,我想将输入数据保存到字符串数组列表中(NOT 在文件或数据库中)。

作为我未来工作的一部分,我将不得不按特定值和 list/display 用户目前输入的所有输入进行搜索。此外,一个输入字段的值应该与其他输入字段相关联。 例如,在第一个字段中,用户写 "Nice",在第二个字段中,他写了多个单词 - "beautiful"、"Excellent"。这意味着最后两个词应该属于第一个词- "Nice"。很像一个 Synonym App.

然而,此时此刻,我的重点是存储输入,这发生在用户单击 Save 按钮时。

代码

Class 实现接口:

class SynonymApp : ISynonym
{
    private List <string[]> allItems = new List <string[]>();

    public void AddSynonyms(IEnumerable<string> synonyms)
    {
        //adding objects at the end of the list. Am I doing right?
        allItems.Add((synonyms.ToArray<string>()));
    }
}

Class 按钮点击事件发生的地方:

private void button1_Click(object sender, EventArgs e)
{
    List<string> userInput = new List<string>();
    string wordInput = textBox1.Text;
    if (wordInput == "") throw new Exception("Please give input");

    char[] emptySpace = new char [] {' ', '\t'};
    string[] synonymInput = textBox2.Text.Split(emptySpace);
    userInput.Add(wordInput);
    userInput.AddRange(synonymInput);
    synonymApp.AddSynonyms(userInput);
}

问题

  1. 通过简单的 Listarray 将字符串输入保存到数组列表中是正确的选择吗? ArrayList 通常有什么作用?
  2. 我的数组列表(即 private List <string[]> allItems = new List <string[]>(); )会根据需要增加大小吗?

如果您真的想要 "own" 其他两个输入中的第一个词,我会使用 Dictionary<string, List<string>>。这将原始词与同义词分开,并使其可搜索。

您说得对,您需要多维存储(数组列表、数组数组等)。或者,更好的是,创建一个 SynonymEntry class:

public class SynonymEntry
{
    public string EntryWord { get; set; }
    public List<string> Synonyms { get; set; }
}

然后您可以创建一个简单的 List<SynonymEntry> 来存储所有数据。

列表与数组 - 如果我知道以后永远不会添加新信息,我只会使用数组。

你没有告诉你的应用程序的上下文(你只是说非常像同义词应用程序),但如果你真的存储同义词,知道同义词是二元关系;即如果 A 是 B 的同义词,那么 B 也是 A 的同义词。

在这种情况下,我只是将所有单词(无论是主要单词还是同义词)存储在一个大的字符串列表 (List<string>) 中。除了这个列表,我还会将另一个存储关系存储在 List<(int ,int)> 中,在每个元组中存储主词和同义词的索引。

如果你使用数据库来序列化这个列表(你说你不会),这将转化为两个简单的表;单词 (int ID, varchar Word) 和关系 (int ID1, int ID2).

您可以改用 List>,它会根据需要增长。另一种解决方案可能是 Dictionnary> 您应该尝试选择正确的。字符串数组不像列表那样容易增长。

Is the right choice to save the string input into a List of Array over just a simple List or an array? What does a List of Array do, in general?

在你的情况下,不。总是尽量让事情简单。我从未见过 List<string[]> 的用法。数组和列表是两个不同的东西,不应该结合使用。即使你使用它也很难维护、调试并且不会是最优的。

Will my List of array (i.e. private List <string[]> allItems = new List <string[]>();) grow in size according to the needs?

是的,但除非有特定原因,否则我会尽量避免使用 List<string[]>


IMO,您应该将代码组织成 类 并使用 HashSet,因为它通常比 List.

class MySynonyms
{
    public string Word { get; set; }
    public HashSet<string> Synonyms { get; set; }
}

希望对您有所帮助。