2010-12-15 98 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

我建議你先從一些更文明縮進。以目前的形式來看是很痛苦的。 – 2010-12-15 04:36:02

+0

你應該能夠在不瞭解linq的情況下編寫可讀代碼,特別是因爲我剛剛做過。 – 2010-12-15 04:44:29

+0

@bemace:謝謝....... – bala3569 2010-12-15 04:46:14

回答

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

正常運行... – bala3569 2010-12-15 05:34:15

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 2010-12-15 06:19:28