- Home /
My Generic function using LINQ(orderBy thenBy)Not working on IOS
I have written this function
public static Dictionary<TKey,TValue> MySort<TKey,TValue>(this Dictionary<TKey,TValue> source, Type typeOfObject, bool isAscending = false, params string[] param)
{
if(param.Length == 0)
return source;
if (isAscending)
{
var temp = source.OrderBy (a => (typeOfObject.GetProperty (param [0])).GetValue (a.Value, null));
for (int i=1; i<param.Length; i++)
{
var myVar = i;
temp = temp.ThenBy((a => (typeOfObject.GetProperty(param[myVar])).GetValue (a.Value, null)));
}
return temp.ToDictionary(a=>a.Key, a=>a.Value);
}
else
{
var temp = source.OrderByDescending (a => (typeOfObject.GetProperty (param [0])).GetValue (a.Value, null));
for (int i=1; i<param.Length; i++)
{
var myVar = i;
temp.ThenByDescending((a => (typeOfObject.GetProperty(param[myVar])).GetValue (a.Value, null)));
}
return temp.ToDictionary(a=>a.Key, a=>a.Value);
}
}
I had to use sorting again and again all over my Project so i made this generic function. It works perfectly fine on all platforms except IOS it throws this exception
Attempting to JIT compile method 'System.Linq.Enumerable:OrderBy, object> (System.Collections.Generic.IEnumerable`1>,System.Func`2, object>)' while running with --aot-only.
I did some googling seems there is some solution to it. And an plugin available on asset store but i dont want to use it. (Well is there is no other option i can use it). I can do it without using LINQ but then i dont know how to do this genericly like this. Im using using 4.6. Are linq methods orderby thenby supported on IOS in this verrsion of Unity and MOno if yes then how can i make my function work. If not then what is the best alternative approach.
It use to be that Linq on iOS would not run.
Best is to come up with your own method. OrderBy/Then by are similar to Array.Sort.
var temp = Array.Sort (source, a => (typeOfObject.GetProperty (param [0])).GetValue (a.Value, null));
Answer by hippogames · Nov 01, 2015 at 10:54 PM
ThenBy is not AOT free so try my workaround. I'm sorting my items by [Type] then by [Price]
Items = Items.OrderBy(i => i.Type).ToList();
for (var j = 0; j < Items.Count - 1; j++) // ordering ThenBy() AOT workaround
{
for (var i = 0; i < Items.Count - 1; i++)
{
if (Items[i].Type == Items[i + 1].Type && Items[i].Price > Items[i + 1].Price)
{
var temp = Items[i];
Items[i] = Items[i + 1];
Items[i + 1] = temp;
}
}
}