【问题标题】:searching through and adding to an alphabetized list搜索并添加到按字母顺序排列的列表
【发布时间】:2017-01-13 07:25:57
【问题描述】:

我的数据库包含一个 csv 文件。我想让它按第一列的字母顺序排列,这样在搜索时,当我越过列表中可以找到搜索项的位置时,我就可以停下来。

设置:我已将整个 csv 文件读入一个名为 fullDB 的 List<string>,并且我有一个名为 itemToFind 的搜索字符串。这是我的搜索代码:

public string[] isFoundInDB(List<string> fullDB, string itemToFind)
{
    for (int i = 0; i < fullDB.Count; i++)
    {
        string[] line = fullDB[i].Split(',');

        if (itemToFind.CompareTo(line[0]) < 0)
        {
            return new string[] { "-1", i.ToString(), "-1", "-1", "-1", "-1" }; //not found
        }

        if (line[0] == itemToFind)
        {
            return new string[] { i.ToString(), line[0], line[1], line[2], line[3], line[4] };
        }
    }

    return new string[] { "-1", fullDB.Count.ToString(), "-1", "-1", "-1", "-1" }; //not found
}

因此,这将给我在数据库中找到它的索引,或者它会给我 itemToFind 过去按字母顺序排列的索引。如果找到,我会修改那里的值。如果没有找到,我使用List.Insert按字母顺序将其插入正确的位置

我的问题是,如果在数据库中找不到 itemToFind,执行我当前的List.Insert 或执行List.Add 是否更有效,然后在我完成添加后对整个内容进行排序事物?我可能会使用此代码对整个数据库进行排序:

IEnumerable<string> query =
    from line in fullDB
    let x = line.Split(',')
    orderby x[0]
    select x[0] + "," + x[1] + "," + x[2] + "," + x[3] + "," + x[4];

fullDB = query.ToList();

或者还有其他更好的方法吗?

使用 C#、.NET 框架 4.0

【问题讨论】:

  • 如果您的代码有效,最好在 codereview.stackexchange.com 上询问,不过在询问之前请仔细检查

标签: c# list search


【解决方案1】:

我会使用以第一列作为键的 SortedDictionary:

List<string> lines = ... // read csv file

SortedDictionary<string, string> sortedLines = new SortedDictionary<string, string>();
foreach (string line in lines)
{
    string[] fields = line.Split(',');
    sortedLines[fields[0]] = line;
}

然后你就可以进行 O(log n) 搜索了:

string foundLine;
if (sortedLines.TryGetValue(itemToFind, out foundLine))
{
    ... // handle the found line
}
else
{
    // add a new line:
    string newLine = // ...
    sortedLines.Add(itemToFind, newLine);
}

如果第一列不是唯一的,您可以使用:

SortedDictionary<string, List<string>>

【讨论】:

  • 对不起,迟到的评论。这完美地工作并且非常快。谢谢!
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多