ファイルフォルダーに次のファイル名があります
1000_A.csv
1000_B.csv
1000_C.csv
1001_A.csv
1001_B.csv
同じ ID で始まるファイル名をリストに追加する必要があります。次に、ID をキーとしてリストをディクショナリに追加する必要があります。
例:
list x contains "1000_A.csv", "1000_B.csv", "1000_C.csv" これを ID 1000 のキーとして辞書に追加してください。
ファイルフォルダーに次のファイル名があります
1000_A.csv
1000_B.csv
1000_C.csv
1001_A.csv
1001_B.csv
同じ ID で始まるファイル名をリストに追加する必要があります。次に、ID をキーとしてリストをディクショナリに追加する必要があります。
例:
list x contains "1000_A.csv", "1000_B.csv", "1000_C.csv" これを ID 1000 のキーとして辞書に追加してください。
を使用できます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());
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);
}
}