c# - 在 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% 准确的,但您需要:
- 从您的 XML 中提取 ID 号
- 将它们传递给扩展方法
- Out 弹出序列中的下一个项目
对于 1,3,4,7 这会产生 2 对于 1,2,3,4 这会产生 5
推荐阅读
- tensorflow - 二进制分类模型无法训练和 auc/accuracy 0.5
- android - 导航动画:slide_in_left 不起作用
- angular - 有角度,Storybook 抛出错误“Zone.js 检测到 ZoneAwarePromise `(window|global).Promise` 已被覆盖。”
- python - 如何在不使用任何第三方库的情况下绘制图案以及输入顺序
- node.js - 使用ejs模板化一个ts文件,类似于generator-jhipster
- redis - 如何在 Debian 上配置多个 Redis 实例
- python - 为什么我得到 -215:Assertion failed 错误消息
- python - 如何通过 ADC 策略阻止赛门铁克端点保护中的哈希并使用 python 创建新规则
- java - 如何修复单元测试缺少方法调用异常?
- java - 尝试在空对象上调用虚拟方法“void android.widget.Button.setVisibility(int)”