gpt4 book ai didi

c# - 如何从字典 C# 返回 tvalues

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:13 24 4
gpt4 key购买 nike

我有一本字典,我需要根据对字符串数组的搜索返回 tvalue。

如何返回与我正在搜索的字符串匹配的 tkey 的 tvalue 以及紧随其后的条目的 tvalue(以计算条目的长度...。这是这样我就可以访问原始文件并导入数据)。

参数 = 要查找的字符串数组。

字典 (dict) 从文件开始设置为 tkey = name, tvalue = bytes。

输入 2 是包含所有信息的文件。

        foreach (var p in parameters)
{
if (dict.ContainsKey(p))
{
int posstart = //tvalue of the parameter found;
int posfinish = //tvalue ofnext entry ;

using (FileStream fs = new FileStream(input[2], FileMode.Open, FileAccess.Read))
{
byte[] bytes = //posstart to pos finish
System.Console.WriteLine(Encoding.Default.GetString(bytes));
}
}
else
{
Console.WriteLine($"error, {p} not found");
}
}

欢迎任何帮助,在此先感谢您。

最佳答案

这里的关键问题是这条评论:

// tvalue of next entry

在 C# 中字典没有排序,所以没有“下一个条目”。 (SortedDictionary 按键而不是值排序,因此这对您没有帮助。OrderedDictionary 可能是您想要的,但让我们假设您有一个 Dictionary 并从那一点开始解决问题。)

让我们将未排序的 name -> offset 数据结构转换为更好的数据结构。

假设我们从这个开始:

    // name -> offset
var dict = new Dictionary<string, int>() {
{ "foo", 100 }, { "bar", 40 }, { "blah", 200 } };

我们将按值对字典进行排序,并将偏移量放入这个排序列表中:

    // index -> offset
var list = new List<int>();

然后我们将制作一个新字典,将名称映射到此列表中的索引:

    // name -> index
var newDict = new Dictionary<string, int>();

让我们从旧字典构建列表和新字典:

    foreach (var pair in dict.OrderBy(pair => pair.Value))
{
newDict[pair.Key] = list.Count;
list.Add(pair.Value);
}

我们还需要最后一个字节的偏移量作为列表中的最后一个东西:

    list.Add(theOffsetOfTheLastByte);

现在我们可以进行两步查找以获取偏移量和下一个偏移量。首先我们按名称查找索引,然后按索引查找偏移量:

    int fooIndex = newDict["foo"]; // 1
int fooOffset = list[fooIndex]; // 100
int nextIndex = fooIndex + 1;
int nextOffset = list[nextIndex]; // 200

有道理吗?

关于c# - 如何从字典 C# 返回 tvalues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com