2013-10-16 27 views
-1

我有以下文件名在我的文件夾需要創建一個字典<INT,列表<string>>使用C#

1000_A.csv 
1000_B.csv 
1000_C.csv 
1001_A.csv 
1001_B.csv 

文件名以相同的ID開始需要被添加到列表,然後在列表需求要添加到字典中與ID爲重點

對於前:
名單x包含「1000_A.csv」,「1000_B.csv」,「1000_C.csv」 ID爲1000的關鍵內容添加到字典請幫忙。

+4

燦你向我們展示你到目前爲止所嘗試過的? – ediblecode

+0

@丹南,但你給了他一個答案! :) –

+1

@ AhmedKRAIEM我只是一個好人,我很確定他是一個她 – ediblecode

回答

0
var folder = GetFolder(); 
var files = new Dictionary<int, List<string>>(); 

foreach (var file in folders) 
{ 
    int id = Convert.ToInt32(file.Substring(0, file.IndexOf('_')); 

    if (files.Any(x => x.Key == id)) 
     files[id].Add(file); 
    else 
    { 
     var newList = new List<string>(); 
     newList.Add(file); 

     files.Add(id, newList); 
    } 
} 
0
var listOfFiles = ...; // assuming you can read the list of filenames 
         // into a string[] or IList<string> 

var d = listOfFiles.GroupBy(f => f.Substring(0, f.IndexOf('_'))) 
    .ToDictionary(g => g.Key, g => g); 
1

您可以使用LINQGroupBy

Dictionary<int, List<string>> idFilenames = fileList 
    .Select(fileName => 
    { 
     string fnwoe = Path.GetFileNameWithoutExtension(fileName); 
     string idPart = fnwoe.Split('_').First(); 
     int id; 
     int.TryParse(idPart, out id); 
     return new { fileName, id }; 
    }) 
    .GroupBy(x => x.id) 
    .ToDictionary(g => g.Key, g => g.Select(x => x.fileName).ToList()); 
0

如CSV您的CSV文件

河套通過你CSV名單列表:

Dictionary<string, int> Dict = new Dictionary<string, int>(); 
List<string> files = new List<string>(); 
foreach (string path CSV) 
{ 
    if(!ContainsKey(path.Substring(0,3)) 
     { 
     files.Add(path); 
     Dict.Add(path.Substring(0,3),files); 
     } 
    else 
     { 
     files.Add(path); 
     Dict[path.Substring(0,3)].Add(file); 
     } 
    } 
相關問題