简化linq查询?
问题描述:
任何人都可以简化这个非常有效地工作....简化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();
}
}
任何建议?
答
看来您的目标是获取具有唯一长度的文件列表。如果是这样的话,我会直接去找散列集(如果内存服务的话它会在封面下使用)并跳过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
答
查看您的代码后,我发现您正在使用繁琐的方法。由于您正在比较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
我建议你先从一些更文明缩进。以目前的形式来看是很痛苦的。 – 2010-12-15 04:36:02
你应该能够在不了解linq的情况下编写可读代码,特别是因为我刚刚做过。 – 2010-12-15 04:44:29
@bemace:谢谢....... – bala3569 2010-12-15 04:46:14