gpt4 book ai didi

c# - 使用二维数组向字典添加值

转载 作者:行者123 更新时间:2023-11-30 18:14:13 24 4
gpt4 key购买 nike

我需要在从文本文件中读取数据时将项目添加到字典中。我希望对于每一行,我的数组中都会有来自该特定行的 x 数据。所以我在我的类中声明了一个二维数组:

Contactsp = new string[][] { };

int number = 0;

使用字典:

Dictionary<string, Contact> dict = new Dictionary<string, Contact>();

从文件中读取:

foreach (var line in File.ReadAllLines(fileName).Where(l =!string.IsNullOrWhiteSpace(l)))
{
for (int j = 0; j < line.Length; j++)
{
for (int i = 0; i < line.Length; i += 9)
{
string hexText = line.Substring(i, 9);
string c = hexText.Substring((hexText.Length - 2));
int length = Convert.ToInt32(c, 16);
Char[] B = new char[length];
string key = line.Substring(i, 4);
string value = line.Substring(i + 9, length);
i += length;

if (!dict.TryGetValue(key, out myContact))
{
myContact = new Contact();
// didn't find a record for this key, so add a new one
dict.Add(key, myContact);
}
dict[key].Contactsp[j][dict[key].number++] = value;
}
j++;
}
}

在运行它时,我在行 dict[key].Contactsp[j][dict[key].number++] = value;

为什么?

最佳答案

根据我们的讨论,我在这里发布一个逻辑,试试看。在您的 Contact 类中,应该有一个 List 来保存每个人的数据。

所以最终的数据结构是, Dictionary<string, Contact> data = new Dictionary<string, Contact>();

foreach (var line in File.ReadAllLines(fileName).Where(l => !string.IsNullOrWhiteSpace(l)))
{
if (lineNum >= 4)
break;

string line = lines[lineNum];

for (int i = 0; i < line.Length; )
{
string key = line.Substring(i, 4);
string hexText = line.Substring(i, 9);
int length = Convert.ToInt16(hexText.Substring(hexText.Length - 2), 16);

string value = line.Substring(i + 9, length);

if (lineNum == 3)
value = FromUnixTime(Convert.ToInt64(value)).ToString();

if (data.ContainsKey(key))
{
data[key].ContactSp.Add(value);
}
else
{
Contact c = new Contact();
c.ContactSp.Add(value);
data.Add(key, c);
}
i = i + 9 + length;
}
}

要转换日期时间,您将需要此方法,(参见 question)

public static DateTime FromUnixTime(long unixTime)
{
return epoch.AddSeconds(unixTime);
}
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

如果你想打印所有值(用于调试)

//and to print all values
foreach(string code in data.Keys)
{
Console.WriteLine("For Code: " + code);
foreach(string value in data[code].ContactSp)
{
Console.WriteLine(" " + value);
}
}

关于c# - 使用二维数组向字典添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673379/

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