我在VS 2010中使用C#4.0,試圖產生n個對象的交集或聯合。c#交叉點和聯盟不能正常工作
下正常工作:
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();
}
}
我確信我俯瞰明顯的東西 - 我看不出它是什麼!
嘗試移動環路內codesTemp'的'的聲明,即'IEnumerable的 codesTemp = dataContextCommonCodes.ICD1 ...'。 –
2013-04-07 21:34:22
感謝Joachim,很好的想法。可悲的是,這沒有什麼區別。 – 2013-04-07 21:39:07
錯過了一件事情,您還需要''tmpItem = item;'並在'dataContextCommonCodes'Linq表達式中使用'tmpItem'而不是'item'。 – 2013-04-07 21:49:17