[英]Get data from csv to dictionary c#
我需要從csv到字典獲取數據,但是當我嘗試編譯此代碼時,我收到錯誤消息“已經添加了具有相同鍵的項。” 怎么做 ? `
Dictionary<string, string> dic = new Dictionary<string, string>();
public void AddToDic()
{
string line = "";
using (StreamReader sr = new StreamReader(@"words.txt"))
{
while (sr.Peek() != -1)
{
line = line + sr.ReadLine();
string[] splitted = line.Split(' ');
dic.Add(splitted[0], splitted[1]); //ERROR An item with the same key has already been added.
}
}
}
//text in words.txt is like: "car auto" newline "water voda" etc...
請嘗試以下檢查:
if(!dic.ContainsKey(splitted[0])
dic.Add(splitted[0], splitted[1]);
由於您沒有向我們顯示您要解析的文件的內容,因此我們只能猜測。 這里是我的猜測(后面跟一個解決方案):
因為一本字典,需要獨特的密鑰和文件可能包含同一個鍵多次有可能每個鍵多個值。 因此,更好的數據結構可能是: Dictionary<string, string[]>
。
您可以使用File.ReadLines
或File.ReadAllLines
來讀取文件的行,然后使用LINQ將其轉換為字典:
Dictionary<string, string[]> result =
File.ReadLines("words.txt")
.Select(line => line.Split(' '))
.GroupBy(arr => arr[0])
.ToDictionary(gr => gr.Key,
gr => gr.Select(s => s[1]).ToArray());
說明:讀取一行后,它被拆分為string[]
。 結果按第一個單詞分組,第一個單詞將成為字典的關鍵字。 每個組是一個IEnumerable<string[]>
並且僅來自每個陣列的所述第二值被選擇成的結果。
BTW:如果更換ReadLines
與ReadAllLines
文件將立即被讀取,然后它會在處理之前被關閉。 ReadLines
讀取各行,並在處理文件時使其保持打開狀態。
字典鍵必須唯一
if(!dic.ContainsKey(splitted[0]))
dic.Add(splitted[0], splitted[1]); //ERROR An item with the same key
將阻止錯誤的發生,但可能不會阻止您想要的行為。 想想你要如何處理重復鍵(失敗文件的加載,只存儲您看到的第一個關鍵,只存儲最新的一個,你看,追加的鍵名的末尾一個計數器,如果有一個碰撞)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.