Let's say the following types:
public class Object { }
public class GameObject : Object { }
public class Component : Object { }
public class Transform : Component { }
And two Type[]
var t1 = new [] { typeof(Object), typeof(Component) };
var t2 = new [] { typeof(GameObject), typeof(Transform) };
And the extension method:
Console.Writeline(t1.IsAssignableFrom(t2); // prints true
I wrote the method in a basic way:
public static bool IsAssignableFrom(this Type[] to, Type[] from)
{
if (to.Length != from.Length) return false;
for (int i = 0; i < to.Length; i++) {
if (!to[i].IsAssignableFrom(from[i]))
return false;
}
return true;
}
But couldn't write it in a LINQ fashion... - Didn't know what methods to use :s
Any ideas?
Thanks!
I suspect you're just looking for:
return to.Length == from.Length &&
to.Zip(from, (t, f) => t.IsAssignableFrom(f))
.All(x => x);
The call to Zip
here just zips the first elements of both sequences with each other, then the second elements, etc - applying the operation specified as (t, f) => t.IsAssignableFrom(f)
on each pair. The All
just checks that the resulting sequence is all true.
Depending on how you're calling this, you might want to make it an error for the lengths to be different, instead of just returning false
:
if (to.Length != from.Length)
{
throw new ArgumentException("...");
}
return to.Zip(from, (t, f) => t.IsAssignableFrom(f))
.All(x => x);
See more on this question at Stackoverflow