简化linq查询?

时间:2010-12-15 04:31:01

标签: c# 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();
    }
}

任何建议??

2 个答案:

答案 0 :(得分: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,您也可以使用Count,因为它不会像您在示例中那样涉及迭代整个集合,但我发现Any也传达了意图,并且由于小而不太可能降低性能其他地方的变化。

答案 1 :(得分: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);