我的数据库包含一个 csv 文件。我想让它按第一列的字母顺序排列,这样在搜索时我可以在经过列表中找到搜索项的位置时停止。
设置:我已将整个 csv 文件读入 List<string>
称为 fullDB,我有一个名为 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
最佳答案
我会使用以第一列作为键的 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>>
关于c# - 搜索并添加到按字母顺序排列的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41629397/