如何在数组中获取类似的文件数据? [英] How to get similar file data in array?
问题描述
我有数组中的文件名数据。如下所示,
AA_2.csv
AA_3.csv
AB_1.csv
AB_2.csv
AB_3.csv
AD_1.csv
现在名称AA,AB ,AD是我的设备名称,1,2,3是特定设备上传的文件。意味着AA_2.csv和AA_3.csv是由设备AA等上传的文件。
现在我想为每个设备创建一个设备名称文件,其中包含3个文件1,2的数据, 3仅当同一设备的所有三个文件都存在时。我怎样才能做到这一点。
我尝试过的事情:
尝试循环遍历所有文件,但没有得到确切的ans。
I have data of file names in array. like below,
AA_2.csv
AA_3.csv
AB_1.csv
AB_2.csv
AB_3.csv
AD_1.csv
Now in above name AA,AB,AD are my device names and 1,2,3 are the files uploaded by specific devices. Means AA_2.csv and AA_3.csv are files uploaded by device AA and so on.
Now I want to to create one file of device name per device which have data of respective 3 files 1,2,3 only if all three files present of same device. how can I achieve that.
What I have tried:
tried by looping through all files but didnt get exact ans.
推荐答案
使用 DirectoryInfo.GetFiles [ ^ ]过滤(参见示例代码)具体设备文件然后将它们附加到单个文件中。
Use the DirectoryInfo.GetFiles[^] to filter in (see the sample code) specific device files and then append them into a single one.
除了 CPallini [ ^ ],您可以使用Directory.GetFiles Method(System.IO)| Microsoft Docs [ ^ ]也是+ linq查询。看看:
In addition to solution #1 by CPallini[^], you can use Directory.GetFiles Method (System.IO) | Microsoft Docs[^] too + linq query. Take a look:
string[] files = Directory.GetFiles(@"yourPathHere", "*.csv", SearchOption.TopDirectoryOnly); // it will return an array of names: {"AA_2.csv", "AA_3.csv", "AB_1.csv", "AB_2.csv", "AB_3.csv", "AD_1.csv"} including a path
string pattern = @"[A-Z]{1,}";
var filesGrouppedByDevices = files
.GroupBy(x=>Regex.Match(x, pattern).Value)
.Where(grp=>grp.Count()==3)
.Select(grp=>new
{
DeviceName = grp.Key,
DeviceFiles = grp.Select(x=>x).ToList()
})
.ToList();
foreach(var deviceinfo in filesGrouppedByDevices)
{
Console.WriteLine("{0}", deviceinfo.DeviceName);
foreach(var file in deviceinfo.DeviceFiles)
{
Console.WriteLine("\t{0}", file);
}
}
显示:
Displays:
AB
AB_1.csv
AB_2.csv
AB_3.csv
现在你所要做的就是实现从文件加入数据的方法。
欲了解更多详情,请参阅:
如何:阅读文件中的文字| Microsoft Docs [ ^ ]
如何:将文本写入文件Microsoft Docs [ ^ ]
这篇关于如何在数组中获取类似的文件数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!