在C#中索引,搜索和存储信息的最佳方式

时间:2014-03-13 00:11:10

标签: c# xml linq

我正在编写一个需要快速索引和存储有关文件信息的应用程序。我目前正在使用XML来使用以下代码存储信息:

        XmlTextWriter xtw;
        xtw = new XmlTextWriter(FilePath, Encoding.UTF8);
        xtw.WriteStartDocument();
        xtw.WriteStartElement("ApplicationIndex");
        xtw.WriteEndElement();
        xtw.Close(); 

        XmlDocument xd = new XmlDocument();
        FileStream lfile = new FileStream(FilePath, FileMode.Open);
        xd.Load(lfile);
        XmlElement cl = xd.CreateElement("Application");
        cl.SetAttribute("Name", ApplicationName);
        XmlElement na = xd.CreateElement("Path");
        XmlText natext = xd.CreateTextNode(ApplicationPath);
        na.AppendChild(natext);
        cl.AppendChild(na);
        XmlElement na1 = xd.CreateElement("UseCount");
        XmlText natext1 = xd.CreateTextNode("0");
        na1.AppendChild(natext1);
        cl.AppendChild(na1);
        XmlElement na2 = xd.CreateElement("SearchTerm");
        XmlText natext2 = xd.CreateTextNode(ApplicationName.ToLower());
        na2.AppendChild(natext2);
        cl.AppendChild(na2);
        xd.DocumentElement.AppendChild(cl);
        lfile.Close();
        xd.Save(FilePath);

这适用于创建文件和存储数据,但是我很难快速搜索数据,因为文档中有几百个节点。我已经尝试使用Linq to XML来实现这个代码:

        listBox1.Items.Clear();
        var doc = XDocument.Load(filePath);
        foreach (var child in doc.Descendants("SearchTerm"))
        {
            if (child.Value.Contains(textBox1.Text.ToLower()))
            {
                listBox1.Items.Add(child.Value);
            }
        }

这非常快,但我似乎无法获得有关所选节点的任何信息。例如,我想根据UseCount对返回的结果进行排序(计数越高,列表越高)。无论如何用XML或任何其他技术来实现这一目标吗?

这就是XML文件的样子:

    <?xml version="1.0" encoding="utf-8"?>
<ApplicationIndex>
  <Application Name="Google Chrome">
    <Path>C:\Program Files\Google\Chrome\Chrome.exe</Path>
    <UseCount>0</UseCount>
    <SearchTerm>google chrome</SearchTerm>
  </Application>
  <Application Name="Mozilla Firefox">
    <Path>C:\Program Files\Mozilla\Firefox\Firefox.exe</Path>
    <UseCount>0</UseCount>
    <SearchTerm>mozilla firefox</SearchTerm>
  </Application>
</ApplicationIndex>

1 个答案:

答案 0 :(得分:3)

您可以按降序顺序按UseCount对元素进行排序,如下所示:

var doc = XDocument.Load(filePath);
var elements = doc.Descendants("Application")
               .OrderByDescending(x => (int)x.Element("UseCount"));

要按给定SearchTerm搜索记录,您可以执行以下操作:

var element = doc.Descendants("Application")
             .FirstOrDefault(x => (string)x.Element("SearchTerm") == value);

if(element != null)
{
    // record found
}