Regex를 사용하여 데이터의 파일 이름을 파싱하고 Linq를 사용하여 Duplicates 또는 Distinct 레코드를 얻을 수 있습니다.
POCO : 기본 OrderBy
이 알파벳 순으로 작동하기 때문에 당신은 가중치 함수가 필요합니다
public class FileData
{
public string Original { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public int Weight { get { return GetWeight(Type); } }
private static int GetWeight(string option)
{
// This will put the files in order by pdf, doc, txt, etc
switch(option)
{
case "pdf":
return 0;
case "doc":
return 1;
case "txt":
return 2;
default:
return 3;
}
}
}
. 이렇게하면 어떤 파일이 더 중요한지 지정할 수 있습니다.
코드 : 또한
// you can substitute this with Directory.GetFiles
// e.g. var files = Directory.GetFiles("Path/To/Files");
var files = new []
{
"BkUpSalesReportJan2011(txt).zip",
"BkUpSalesReportJan2011(pdf).zip",
"BkUpSalesReportJan2011(doc).zip",
"BkUpSalesReportFeb2011(txt).zip",
"BkUpSalesReportMar2011(doc).zip",
"BkUpSalesReportMar2011(pdf).zip"
};
var pattern = @"(?<FileName>.+)\((?<FileType>\w+)\)\.zip";
// (?<FileName>.+) Match the first part in a named group
// \(Match the first open parenthesis
// (?<FileType>\w+) Match the txt/pdf/doc/whatever in a named group
// \) Match the closing parenthesis
// \.zip Match a period followed by the zip
var matchedFiles = files.Select(f => Regex.Match(f, pattern))
.Where(m => m.Success)
.Select(f =>
new FileData
{
Type = f.Groups["FileType"].Value,
Name = f.Groups["FileName"].Value,
Original = f.Value
}
).ToList();
// Group all the files by the name e.g. BkUpSalesReportJan2011
// Transform the group into order and take the first record
// Take the original file name to get the originals
var distinct = matchedFiles.GroupBy(f => f.Name)
.Select(g => g.OrderBy(f => f.Weight).First())
.Select(f => f.Original);
// Group all the files by the name e.g. BkUpSalesReportJan2011
// Transform the group into order and skip the first record
// Since the records are still in a nested IEnumerable we need to flatten it
// Take the original file name to get the duplicates
var duplicates = matchedFiles.GroupBy(f => f.Name)
.Select(g => g.OrderBy(f => f.Weight).Skip(1))
.SelectMany(g => g)
.Select(f => f.Original);
참조 :
Directory.GetFiles
** TL; DR **. 구체적인 질문이 있습니까? 아니면 일반적인 지침을 묻고 있습니까? 전자는 주제에 관한 것이고 후자는 주제와 관련이 없을 것입니다. –
글쎄, 빅뱅이 일어난 이유를 설명하는 대신 다음 가이드를 따라 게시하십시오. 오류, 오류로 이어지는 코드, 문제 발생시의 질문. 모든 것을 설명하는이 사업은 내가 모든 것을 건너 뛰고 싶어하게 만듭니다. – TheGeekZn
귀하의 질문은 유효하고 구체적인 질문과 휴식으로 구성되어 있습니다. 텍스트의 75 %는 완전히 관련이 없으며 여기에 정말 감사하지 않습니다 (블로그 나 다른 것이 아닙니다). 의미있는 질문을 추출하고 나머지는 삭제하십시오. – Andrey