英文:
Clear all arrays inside given JObject
问题
我需要清空给定 JObject 中的所有数组。是否有更好的方法来实现这个目标。
var jobject = request.selectToken(keyPath) as JObject;
foreach (var token in jobject.Descendants().Where(jt => jt is JArray).ToList())
{
var referenceToken = token as JArray;
referenceToken.Clear();
}
我还尝试过重新分配 **referenceToken = new JArray()**,但这当然会导致编译错误。
英文:
I require to clear/empty all arrays inside a given JObject. Is there a better way to achieve this.
var jobject = request.selectToken(keyPath) as JObject;
foreach (var token in jobject.Descendants().Where(jt => jt is JArray).ToList())
{
var referenceToken = token as JArray;
referenceToken.Clear();
}
I also tried reassigning referenceToken = new JArray(), but this of course gives compilation errors.
答案1
得分: 3
你可以移除 ToList
。同时,你也可以通过使用 OfType
移除类型检查。
foreach (var array in jobject.Descendants().OfType<JArray>())
array.Clear();
如果你只需要根级别的数组属性,那么你可以使用 jobject.Children()
,它更快。
英文:
You can remove the ToList
. And you can also remove the type-check by using OfType
foreach (var array in jobject.Descendants().OfType<JArray>())
array.Clear();
If you only need root-level properties which are arrays then you can instead use jobject.Children()
which is faster.
答案2
得分: 1
你可以使用此代码来删除整个项,而不仅仅是清除项的值。
英文:
you can use this code to remove the whole item, not just to clean an item value.
jobject.Descendants()
.Where(x => x.Any(x => x.Type == JTokenType.Array))
.ToList()
.ForEach(tr => tr.Remove());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论