首页 > 解决方案 > 在 XML 记录中获取第一个免费 ID 的最简单方法

问题描述

我正在向 XML 文件添加记录。我想将 Id 属性设置为第一个自由值或最后一个值 + 1。(如果 id 是 1、3、4、7,那么我要设置的 id 是 2,如果是 1、2、3、4,那么它是 5)。

这是我的xml结构

<ArrayOfDirectory>
  <Directory Id="0">
    <DirectoryPath>E:\tempFolder1</DirectoryPath>
    <Info>some info</Info>
  </Directory>
  <Directory Id="2">
    <DirectoryPath>C:\tempFolder2</DirectoryPath>
    <Info>some info</Info>
  </Directory>
</ArrayOfDirectory>

这样我将记录插入文件

        WatchedDirectory directoryToSave = (WatchedDirectory)entity;
        XElement newDirectory = new XElement("WatchedDirectory",
            new XAttribute("Id", directoryToSave.Id),
            new XElement("DirectoryPath", directoryToSave.DirectoryPath),
            new XElement("Info","some info"));

        XDocument xDocument = XDocument.Load(DirectoryXmlPath);
        xDocument.Root.Add(newDirectory);
        xDocument.Save(DirectoryXmlPath);

我的问题是添加新记录时设置第一个免费 ID 的最简单方法是什么?

标签: c#.netxmllinq-to-xml

解决方案


您可以使用以下扩展方法:

public static int GetNextSequenceNum(this IEnumerable<int> sequence)
{
    var nums = sequence.OrderBy(i => i).ToList();
    var max = nums[nums.Count - 1];
    return Enumerable.Range(0, max + 1)
        .GroupJoin(nums, i => i, i => i, (i, found) =>
        {
            var f = found.ToList();
            if (f.Count == 0)
                return i;
            else
                return (int?)null;
        })
        .First(i => i.HasValue)
        .Value;
}

我不保证这是 100% 准确的,但您需要:

  1. 从您的 XML 中提取 ID 号
  2. 将它们传递给扩展方法
  3. Out 弹出序列中的下一个项目

对于 1,3,4,7 这会产生 2 对于 1,2,3,4 这会产生 5


推荐阅读