我有以下文件名在我的文件夾需要創建一個字典<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的關鍵內容添加到字典請幫忙。
我有以下文件名在我的文件夾需要創建一個字典<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的關鍵內容添加到字典請幫忙。
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);
}
}
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);
您可以使用LINQ
的GroupBy
:
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());
如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);
}
}
燦你向我們展示你到目前爲止所嘗試過的? – ediblecode
@丹南,但你給了他一個答案! :) –
@ AhmedKRAIEM我只是一個好人,我很確定他是一個她 – ediblecode