在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的最简单方法是什么?

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

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

最新更新