Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将嵌套数组中的值添加到uniques列表中效率更高_C#_Arrays_Performance - Fatal编程技术网

C# 将嵌套数组中的值添加到uniques列表中效率更高

C# 将嵌套数组中的值添加到uniques列表中效率更高,c#,arrays,performance,C#,Arrays,Performance,我用的是C#, 我得到了一个带有嵌套数组的文档——这里是其数据结构的简化示例(作为json)—— 我需要在这个文档上运行,对于每一行,在它的嵌套项上运行,对于每个嵌套项,将nestedValue添加到一个新列表中,并且只对唯一的值这样做(没有重复) 最简单的方法是执行以下操作: foreach(line in lines) foreach(nestedItem in line.nestedItems) check if nestedItem.nestedValue exis

我用的是C#, 我得到了一个带有嵌套数组的文档——这里是其数据结构的简化示例(作为json)——

我需要在这个文档上运行,对于每一行,在它的嵌套项上运行,对于每个嵌套项,将
nestedValue
添加到一个新列表中,并且只对唯一的值这样做(没有重复)

最简单的方法是执行以下操作:

foreach(line in lines) 
   foreach(nestedItem in line.nestedItems)
       check if nestedItem.nestedValue exists already exists in my new list,
       if not add it.
我想知道是否有更有效的方法来做到这一点。 我可能会有相当大的流量通过这个逻辑

一点背景:
我试图提取一组文档ID,然后通过redis缓存锁定这些资源,这样共享数据就不会同时得到处理。但我想让这个锁定/解锁机制的逻辑尽可能高效,这是其中的一部分。

试图在列表中找到重复项,需要花费很多。从a进行此类检查要容易得多,也要快得多(我将研究并更新检索时间——找不到硬值,但理论上,基于哈希的数据结构应该是O(1),列表应该是O(N))

警告:哈希集无法排序,不允许重复

因此,您可以保留代码并执行以下操作

foreach(line in lines) 
   foreach(nestedItem in line.nestedItems)
       // Just add to the HashSet. If it exists it will not add it at all
返回值:布尔值

如果元素添加到HashSet对象,则为true

如果元素已存在,则为false

引用文件

HashSet类基于数学集和 提供与访问密钥类似的高性能设置操作 字典或哈希表集合的。简而言之 就术语而言,HashSet类可以被视为 没有值的字典集合

哈希集集合未排序,不能包含重复项 元素。如果顺序或元素重复比 应用程序的性能,考虑使用列表类 以及排序方法


要转换为列表,只需使用Xpath Json查询就可以获得更好的性能。 以Newtonsoft库为例

JObject json=JObject.Parse(jsonText);
var nestedValuesFromJson=json.SelectTokens(“$.lines.nestedItems[:].nestedValue”).Values().Distinct();
全例


或者您可以直接
Add()
it并检查返回值。如果返回
false
,则表示该项已存在。您对此进行了测量吗?或者只是猜测它可能更好?只是猜测。可以找到一个不加载所有json的库来浏览它。它导致更小的内存占用,特别是对于非常大的json
foreach(line in lines) 
   foreach(nestedItem in line.nestedItems)
       // Just add to the HashSet. If it exists it will not add it at all