清空给定 JObject 内的所有数组。

huangapple go评论66阅读模式
英文:

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());

huangapple
  • 本文由 发表于 2023年4月4日 17:48:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定