需要使用 c# 创建字典>

本文关键字:int string List 字典 创建 | 更新日期: 2023-09-27 18:35:32

我的文件夹中有以下文件名

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 为键的字典中 请帮忙。

需要使用 c# 创建字典<int、List<string>>

你可以使用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());
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 );
例如 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);
      }
  }