【发布时间】:2013-04-07 21:28:19
【问题描述】:
我在 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);
但是,以下不是。这些是代码 sn-ps。
我的班级是:
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();
}
}
我确定我忽略了一些明显的东西 - 我只是看不到它是什么!
【问题讨论】:
-
尝试在循环内移动
codesTemp的声明,即IEnumerable<ICD10Codes> codesTemp = dataContextCommonCodes.ICD1...。 -
谢谢 Joachim,好主意。可悲的是,这没什么区别。
-
错过了一件事,您还需要做
List<string> tmpItem = item;并在dataContextCommonCodesLinq 表达式中使用tmpItem而不是item。
标签: c# linq search intersection