2010-12-15 7 views
0

사람이 ....이 매우 효율적으로 작업 할 수linq 쿼리를 단순화 하시겠습니까?

FileCompareLength myFileCompare1 = new FileCompareLength(); 
var queryList1Only3 = (from file in list1 select file).Except(list2, myFileCompare1); 
var queryList1Only33 = (from file in list2 select file).Except(list1, myFileCompare1); 
var difference1 = queryList1Only3.ToHashSet(); 
difference1.SymmetricExceptWith(queryList1Only33); 
var query4 = difference1.AsEnumerable().OrderBy(x => x.Name); 
if (query4.Count() > 0) { 
    dest.WriteLine("Discrepancies in File Date:"); 
    foreach (var v in query4) { 
     dest.WriteLine(v.Lengh+ "  " + v.FullName); 
    } 
} 

public class FileCompareLength : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo> { 
    public FileCompareLength() { } 
    public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2) { 
     return (f1.Length == f2.Length); 
    } 

    public int GetHashCode(System.IO.FileInfo fi) { 
     return fi.Length.GetHashCode(); 
    } 
} 

어떤 제안을 단순화 할 수 ??

+1

난 당신이 좀 더 문명화 된 들여 쓰기로 시작하는 것이 좋습니다. 현재의 모습을 보면 고통 스럽습니다. –

+0

linq에 대해 많이 모르는 상태에서 읽을 수있는 코드를 만들 수 있어야합니다. –

+0

@bemace : thanks ....... – bala3569

답변

4

고유 한 길이의 파일 목록을 얻는 것이 목표 인 것으로 보입니다. 그렇다면 해시 집합 (메모리가 작동하면 커버 아래에 사용됨)으로 바로 이동하여 LINQ를 건너 뜁니다.

var uniqueFiles = new HashSet<FileInfo>(list1, new FileCompareLength()); 
uniqueFiles.SymmetricExceptWith(list2); 
//you should now have the desired list. 
//as mentioned in the comments, check for any items before sorting 
if (uniqueFiles.Any()) 
{ 
    for (var file in uniqueFiles.OrderBy(x => x.Name)) 
    { 
     //do stuff with file 
    } 
} 

당신은 HashSet의를 사용하는 경우, 당신은 또한 그것이 당신의 예에서와 마찬가지로 전체 컬렉션을 반복 포함하지 것이기 때문에 카운트 사용할 수 있습니다,하지만 난 어떤 전달한다 의도가 단지뿐만 아니라 및 저하 가능성이 적습니다 것을 발견 다른 곳에서는 작은 변화로 인해 성능이 저하 될 수 있습니다.

+0

good working ... – bala3569

1

코드를 살펴본 후 까다로운 방법을 사용하고있는 것으로 나타났습니다. FileInfo.Length을 비교 중이므로 int[]을 예로 사용하겠습니다. 의가 있다고 가정 해 봅시다 :

list1: 1 2 2 5 5 7 (the numbers are lengths of files) 
list2: 2 3 4 7 
list1 except list2(called e1): 1 5 5 
list2 except list1(called e2): 3 4 
SymmetricExceptWith: 1 5 5 3 4 (always e1+e2 because e1/e2 comes from Except) 

는 따라서 코드가 같이 개선 될 수있다 :

var common = list1.Intersect(list2, myFileCompare1); 
var exclusive = list1.Concat(list2).Where(x => !common.Contains(x)) 
            .OrderBy(x => x.Name); 
+0

길이가 다른 파일이 필요합니다. – bala3569

관련 문제