C# 如何创建将字典写入csv文件的通用方法?
我想编写一个函数,接收具有任意键和值类型的字典,并将它们写入csv文件。例如,如果我有以下课程:C# 如何创建将字典写入csv文件的通用方法?,c#,function,C#,Function,我想编写一个函数,接收具有任意键和值类型的字典,并将它们写入csv文件。例如,如果我有以下课程: public class VerificationResult { public enum resInfo { sessionID, testFilePath, testFileName, ID1, ID2, score1, score2, isGood,
public class VerificationResult
{
public enum resInfo
{
sessionID,
testFilePath,
testFileName,
ID1,
ID2,
score1,
score2,
isGood,
isTrue
};
public string[] resData =
new string[Enum.GetNames(typeof (resInfo)).Length];
public VerificationResult(int sessionID,
string testFilePath,
string Id1,
string Id2,
string score1,
string score2,
string isGood)
{
resData[(int) resInfo.sessionID] = sessionID.ToString();
resData[(int) resInfo.testFilePath] = testFilePath;
resData[(int) resInfo.testFileName] =
Path.GetFileNameWithoutExtension(testFilePath);
resData[(int) resInfo.ID1] = Id1;
resData[(int) resInfo.ID2] = Id2;
resData[(int) resInfo.score1] = Score1;
resData[(int) resInfo.score2] = Score2;
resData[(int) resInfo.isGood] = isGood;
resData[(int) resInfo.isTrue] = (Id1 == IsGood).ToString();
}
};
以及定义为:
private Dictionary<int,VerificationResult> verificationResults
专用字典验证结果
我想创建一个通用函数,它能够将这个字典打印到一个csv文件中,并带有值成员的头(在本例中是VerificationResult类的成员)
我决定发送一个数组或值类型成员的枚举作为参数。问题是我不必知道保存我需要的数据数组的值类成员的名称,或者(如果我决定以不同方式实现它)如何遍历未知值类成员并将其打印到文件中。有没有一种方法不使用类似eval的函数就可以做到这一点?我是否尝试过这么做?我是否应该在每次需要时都编写一个特定的函数并保持这种状态?您可以与委托一起指定键和值的字符串表示方式在我的示例中,我创建了一个用于IDictionary的方法
public static class DictionaryExtension {
public static void WriteToCsv<K, V>(
this IDictionary<K, V> dictionary,
string path,
Func<K, string> keyToString,
Func<V, string> valueToString,
string separator) {
StringBuilder content = new StringBuilder();
foreach (KeyValuePair<K, V> keyValuePair in dictionary)
content.AppendLine(string.Join(separator, new List<string> {
keyToString(keyValuePair.Key),
valueToString(keyValuePair.Value)
}));
File.WriteAllText(path, content.ToString());
}
}
以及以下字典:
Dictionary<long, ComplexType> test = new Dictionary<long, ComplexType>();
test.Add(1, new ComplexType { Number = 1, Name = "one"});
test.Add(2, new ComplexType { Number = 1, Name = "two" });
test.Add(3, new ComplexType { Number = 1, Name = "three" });
test.Add(4, new ComplexType { Number = 1, Name = "four" });
1;one
2;two
3;three
4;four
足够写字典了:
Dictionary<long, ComplexType> test = new Dictionary<long, ComplexType>();
test.Add(1, new ComplexType { Number = 1, Name = "one"});
test.Add(2, new ComplexType { Number = 1, Name = "two" });
test.Add(3, new ComplexType { Number = 1, Name = "three" });
test.Add(4, new ComplexType { Number = 1, Name = "four" });
1;one
2;two
3;three
4;four