Skip to main content
 首页 » 编程设计

c# Intersection 和 Union 不能正常工作

2024年02月13日13虾米哥

我在 VS 2010 中使用 C# 4.0 并尝试生成 n 组对象的交集或并集。

以下工作正常:

IEnumerable<String> t1 = new List<string>() { "one", "two", "three" }; 
IEnumerable<String> t2 = new List<string>() { "three", "four", "five" }; 
 
List<String> tInt = t1.Intersect(t2).ToList<String>(); 
List<String> tUnion = t1.Union(t2).ToList<String>(); 
//  this also works 
t1 = t1.Union(t2); 
//  as does this (but not at the same time!) 
t1 = t1.Intersect(t2); 

但是,下面的不是。这些是代码片段。

我的类(class)是:

 public class ICD10 
{ 
    public string ICD10Code { get; set; } 
    public string ICD10CodeSearchTitle { get; set; } 
} 

在以下内容中:

IEnumerable<ICD10Codes> codes = Enumerable.Empty<ICD10Codes>(); 
IEnumerable<ICD10Codes> codesTemp; 
List<List<String>> terms; 
//  I create terms here ---- 
// and then ... 
foreach (List<string> item in terms) 
{ 
    //  the following line produces the correct results 
    codesTemp = dataContextCommonCodes.ICD10Codes.Where(e => item.Any(k => e.ICD10CodeSearchTitle.Contains(k))); 
 
    if (codes.Count() == 0) 
    { 
        codes = codesTemp; 
    } 
    else if (intersectionRequired) 
    { 
        codes = codes.Intersect(codesTemp, new ICD10Comparer()); 
    } 
    else 
    { 
        codes = codes.Union(codesTemp, new ICD10Comparer()); 
    }                 
} 
return codes; 

上面只返回最后搜索的结果。

为了以防万一,我还添加了自己的比较器,但这没有什么区别:

public class ICD10Comparer : IEqualityComparer<ICD10Codes> 
{ 
    public bool Equals(ICD10Codes Code1, ICD10Codes Code2) 
    { 
        if (Code1.ICD10Code == Code2.ICD10Code) { return true; } 
        return false; 
    } 
    public int GetHashCode(ICD10Codes Code1) 
    { 
        return Code1.ICD10Code.GetHashCode(); 
    } 
} 

我确定我忽略了一些明显的东西 - 我只是看不到它是什么!

请您参考如下方法:

此代码:返回代码; 返回一个延迟的可枚举对象。尚未执行任何查询来填充集合。不过,每次通过循环都会执行一些查询以进行计数。

这个延迟执行是一个问题,因为闭包问题......在返回时,item 被绑定(bind)到最后一个循环执行。

通过强制在每个循环执行中执行查询来解决此问题:

if (codes.Count() == 0) 
{ 
    codes = codesTemp.ToList(); 
} 
else if (intersectionRequired) 
{ 
    codes = codes.Intersect(codesTemp, new ICD10Comparer()).ToList(); 
} 
else 
{ 
    codes = codes.Union(codesTemp, new ICD10Comparer()).ToList(); 
}