c# - 在进一步处理之前实现比较两个字符串的逻辑
问题描述
我正在尝试将一些逻辑合并到一个应用程序中,这将提高其性能,但我根本无法找到一种实现它的好方法。所以我有一组我反序列化的 json 文件,所有这些文件都具有相同的结构。
{
urlSouce": """,
"info": [
{
"id": ""
}
]
}
因此,每次我反序列化一个文件时,我都会在一个变量中使用 urlSOurce 并将该值用于 API 请求。但是我知道大多数时候这个 urlSource 是相同的,因此不需要继续发送 API 请求并影响性能,这就是为什么我首先要检查来自当前反序列化文件的 urlSource 是否与以前的文件。
如果是,则无需再次发送 API 请求。我知道我可以在这个逻辑中添加一个布尔标志,但我想不出最好的保存位置。
为了演示我在做什么,我有以下代码。如果有人对需要做什么有任何想法,请帮助我
string previousUrl;
string currentURL;
bool isValueChanged;
currentURL = "test1.com"; //the new URL populated from the deserialized JSON
previousUrl = "test2.com"; //the previously deserialized URL of the file before this
在这里,我对任何反序列化都没有问题
我遇到的问题是如何跟踪 previousURl 值?以及如何操作 booleanFlag?
解决方案
听起来您想在处理之前验证一个字符串以前没有被使用过。
如果是这种情况,您可以简单地将“使用过的”字符串存储在 aDictionary
中,将字符串作为 theKey
并将处理结果作为 the Value
,然后Key
在处理它们之前检查字典是否已经包含任何新字符串的 a 。
下面的方法接受一个string
to process 和一个bool
指定是否使用缓存结果(如果存在)。如果string
字典中不包含 ,或者用户指定useCache = false
,则处理字符串并保存在字典中(连同结果),并返回结果。否则,该字符串的缓存结果将立即返回。
private readonly Dictionary<string, string> cachedResults = new Dictionary<string, string>();
public string GetApiResult(string uri, bool useCachedResult = true)
{
// If we've already encountered this string, return the cached result right away
if (useCachedResult && cachedResults.ContainsKey(uri)) return cachedResults[uri];
// Process the string here
var result = MakeAPICall(uri);
// Save it, along with the result, in our dictionary
cachedResults[uri] = result;
// Return the result
return result;
}
听起来我误解了这个问题。如果您只是想确定一个新字符串是否与遇到的最后一个字符串匹配,那么这也很简单:
private string cachedUri;
private string cachedResult;
public string GetApiResult(string uri, bool useCachedResult = true)
{
// If we've already encountered this string, return the cached result right away
if (useCachedResult && uri == cachedUri) return cachedResult;
// Process the string here
var result = MakeAPICall(uri);
// Save it, along with the result, in our fields
cachedUri = uri;
cachedResult = result;
// Return the result
return result;
}
推荐阅读
- docker - 下面这个例子中 docker 多阶段构建的优势是什么(为什么要这样做?)
- sql - SQL - 按两个匹配的列和一个不同的列过滤
- sql - 将评论行加入单行
- apache-spark - EMR Hudi 无法创建 hive 连接 jdbc:hive2://localhost:10000/
- c - Linux在c中捕获复制粘贴事件
- javascript - 如何优化总阻塞时间高的 vue
- azure-cosmosdb-sqlapi - 使用 Bicep 将多个存储过程部署到 Cosmos
- python - 在 S3 Bucket 中,将一个文件夹中的大量文件移动到多个文件夹中
- javascript - 如何编写一个处理对象的 forEachRight 函数?
- r - 如何使用ggplot按组在奇数比的x轴上创建相等的中断?