我是学习C#的新手并且有一个问题。 我有一个带有测试和分数的txt文件,如下所示
ACT
21.0
SAT
478.9
CLEP
69.1
ACT 32.0
如何将此txt解析为字典并显示如下(删除任何重复项)
ACT 21.0
SAT 478.9
CLEP 69.1
以下是我的尝试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
namespace Generate
{
class generateInputStream
{
static void Main(string[] args)
{
FileManager objfileManager = new FileManager();
FileStream fs = null;
Console.Write("Enter the file path: ");
while (fs == null)
{
string Path = Console.ReadLine();
fs = objfileManager.OpenFile(Path);
}
int
}
}
public class FileManager
{
public FileStream OpenFile(string Path)
{
try
{
return new FileStream(Path, FileMode.Open, FileAccess.Read);
}
catch (Exception e)
{
Console.Write("Problem opening file {0}, please enter a valid path: ", Path);
}
return null;
}
public List<string> ReadLines(FileStream File)
{
List<string> text = new List<string>();
try
{
var streamReader = new StreamReader(File);
}
catch (Exception e)
{
Console.Write(e.Message);
}
return text;
}
static readFileIntoDictionary()
{
StreamReader generateInputStream;
var streamReader = new StreamReader();
SortedDictionary<string, double> dic = new SortedDictionary<string, double>();
string Key = string.Empty;
double Value = 0.0;
while ((Key = streamReader.ReadLine())!= null)
{
Value = Convert.ToInt32(streamReader.ReadLine());
dic.Add(Key, Value);
}
streamReader.Close();
return dic;
}
static displayScoreData()
{
readFileIntoDictionary();
foreach (KeyValuePair<string, double> pair in dic)
{
Console.WriteLine(pair.Key, "-",pair.Value);
}
}
}
}
答案 0 :(得分:0)
这种方法应该对你有所帮助。这里没有错误处理,因此我们假设您的文件格式正确。
public static KeyValuePair<string, decimal>? ReadPair (StreamReader sr)
{
if (sr.EndOfStream) return null;
string key = sr.ReadLine ();
decimal value = decimal.Parse (sr.ReadLine ());
return new KeyValuePair<string, decimal> (key, value);
}
我不知道什么是重复的,同样的密钥?相同的键+值?