我在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);


但是,以下不是。这些是代码段。

我的课是:

 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();
    }
}


我敢肯定,我正在忽略一些显而易见的事情-我只是看不到它是什么!

最佳答案

此代码:return codes;返回延迟的枚举。没有执行任何查询来填充集合。每次通过循环都会执行一些查询以进行计数。

由于关闭问题,延迟执行是一个问题……返回时,item绑定到最后一个循环执行。

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

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();
}

关于c# - C#交集和联合无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15868042/

10-12 12:45