2013-03-05 4 views
0

Directory.GetFiles 및 'StartsWith', 'Contains'및 'Inclus'를 사용하여 파일 이름을 필터링하는보다 효율적인 방법이 있습니까? 'EndsWith'는 내가 현재하고있는 방식이 아닌?'StartsWith', 'Contains'및 'EndsWith'와 함께 'Directory.GetFiles'를 효율적으로 사용하여 파일 이름 필터링

 _files = Directory.GetFiles(_path); 

     if (!String.IsNullOrEmpty(_startsWith)) 
     { 
      _files = _files.Where(x => x.StartsWith(_startsWith)).ToArray(); 
     } 

     if (!String.IsNullOrEmpty(_contains)) 
     { 
      _files = _files.Where(x => x.Contains(_contains)).ToArray(); 
     } 

     if (!String.IsNullOrEmpty(_endsWith)) 
     { 
      _files = _files.Where(x => x.EndsWith(_endsWith)).ToArray(); 
     } 
+2

가장 느린 부분은 항상 'Directory.GetFiles'이며, 이는 거의 불가피합니다. 문자열을 검색하는 것이 상대적으로 무시할 만하지만, 당신이 향상시키고 자하는 것이 아닙니다. –

+1

검색 패턴을 제공 할 수있는 GetFiles() 오버로드가 있습니다. 시도해 보셨습니까? – Jobo

답변

2

게으르며 처음부터 전체 목록을 작성할 필요가 없으므로 Directory.EnumerateFiles()으로 전환해야합니다.

0

나는 다음과 같은 과부하가 당신을 도울 것입니다 생각 :

Directory.GetFiles(strPath, "*" + strFilter, SearchOption.TopDirectoryOnly); // to get behaviour of EndsWith 

Directory.GetFiles(strPath, "*" + strFilter + "*", SearchOption.TopDirectoryOnly); // to get behaviour of Contains 

Directory.GetFiles(strPath, strFilter + "*", SearchOption.TopDirectoryOnly); // to get behaviour of StartsWith 
0

당신이 Linq에 한 줄에 모든 것을 벼락 공부하려는 경우, 다음과 같이 수행 할 수 있습니다

_files = _files.Where(_ => !String.IsNullOrEmpty(_startsWith)).Where(x => x.StartsWith(_startsWith)).ToArray(); 

그러나 위에서 언급했듯이 Directory.GetFiles는 거의 확실하게 여기 코드에서 가장 느린 부분이 될 것이므로 읽기가 더 쉬운 무언가를 고집하는 것이 좋습니다.