我有一个字典和一个 IEnumerable,我想加入 Key 和 OtherThing.Id
这适用于 Xamarin Monodroid 上的简单 linq 连接。然后我们想在 IO 的 App 中使用我们的代码。它抛出了一个异常,我很快就知道了原因。正如 Xamarin Docs 中所解释的,我不能将通用字典与值类型一起使用。
然后,我尝试了第 1.7 章(在此处找到)中 Xamarin 文档中解释的解决方法,并将自己的 IEqualityComparer 实现传递给 Dictionary 的构造函数,例如:
比较器:
public class EqualityComparer<T> : IEqualityComparer<T>
{
#region IEqualityComparer implementation
public bool Equals (T x, T y)
{
return x.Equals (y);
}
public int GetHashCode (T obj)
{
return obj.GetHashCode ();
}
#endregion
}
并将其传递给字典
Dictionary<Int32, Attempt> allAttempts =
new Dictionary<int, Attempt>(new EqualityComparer<int>());
allAttempts.Add (1, new Attempt () {Id=1, Name="attempt for 1"} );
allAttempts.Add (2, new Attempt () {Id=2, Name="attempt for 2"} );
但是错误似乎是在连接中引起的,所以我尝试将比较器也提供给连接:
var result = conditions.Join(
attempts,
c => c.Id,
cA => cA.Key,
(c, cA) => cA.Value,
new EqualityComparer<Int32> ());
但这也给了我以下例外:
got this: System.ExecutionEngineException: Attempting to JIT compile method 'System.Linq.Enumerable/Function1<System.Collections.Generic.KeyValuePair2>:m__56 (System.Collections.Generic.KeyValuePair`2)' while running with --aot-only.
See http://docs.xamarin.com/ios/about/limitations for more information.
at System.Linq.Enumerable.ToLookupKeyValuePair2,Int32,KeyValuePair2<IEnumerable%601%20source,%20System.Func%602%20keySelector,%20System.Func%602%20elementSelector,%20IEqualityComparer%601%20comparer> [0x00079]
in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System.Linq/Enumerable.cs:2977
at System.Linq.Enumerable.ToLookupKeyValuePair`2,Int32<IEnumerable%601%20source,%20System.Func%602%20keySelector,%20IEqualityComparer%601%20comparer> [0x00000]
in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System.Linq/Enumerable.cs:2945
at System.Linq.Enumerable+c__Iterator184[Drallo.ChallengeEngine.Condition,System.Collections.Generic.KeyValuePair2[System.Int32,Drallo.ChallengeEngine.Attempt.ConditionAttempt],System.Int32,Drallo.ChallengeEngine.Attempt.ConditionAttempt].MoveNext () [0x00023]
in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System.Linq/Enumerable.cs:1157
在这里您可以找到我为重现此问题而设置的 ios 测试项目: https ://github.com/stestaub/TestLinqJoins/blob/master/TestLinqJoins/JoinWithDictionary.cs
在这种情况下有什么问题,将来我该如何解决/避免?我仍然更喜欢使用 linq。
感谢您的任何帮助和提示