- How can I use Where<T> extension method when T is unknown at compile time
- IEnumerable<object> NewValueSubCollection = (IEnumerable<object>)NewValue.GetType().GetProperty(col.Name).GetValue(NewValue, null);
- //Where col is a property of an object of type (IEnumerable<???>)
- foreach (var line in ((IEnumerable<object>)col.GetValue(originalEntity, null)).ToList<object>())
- {
- Type lineType = ObjectContext.GetObjectType(line.GetType());
- var lineEntitySet = context.GetEntitySet(lineType);
- EntityKey lineKey = context.CreateEntityKey(lineEntitySet.Name, line);
- if (NewValueSubCollection.Where(lineKey).Count() == 0) //See bellow
- context.DeleteObject(line);
- }
- public static class LinqExtension
- {
- //Enable searching in a collection is an entity Key exist... and retrieve info.
- public static IEnumerable<T> Where<T>(this IEnumerable<T> source,EntityKey key)
- {
- return Enumerable.Where(source, CreateFilterExpressionBasedOnKey<T>(key).Compile());
- }
- private static Expression<Func<TInput, bool>> CreateFilterExpressionBasedOnKey<TInput>(Type sourceType, EntityKey key)
- {
- var param = Expression.Parameter(sourceType, "");
- Expression myFilter = Expression.Constant(true);
- if (key != null)
- {
- foreach (var item in key.EntityKeyValues)
- {
- Expression Left = Expression.PropertyOrField(param, item.Key.ToString());
- Expression Right = Expression.Constant(item.Value);
- myFilter = Expression.AndAlso(myFilter, Expression.Equal(Left, Right));
- }
- }
- return Expression.Lambda<Func<TInput, bool>>(myFilter, param);
- }
- }
- Type generic = typeof(Collection<>);
- Type typeArgs = (NewValue.GetType().GetProperty(col.Name).GetValue(NewValue, null)).GetType().GetGenericArguments()[0];
- Type constructed = generic.MakeGenericType(typeArgs);
- object o = Activator.CreateInstance(constructed);
- o = NewValue.GetType().GetProperty(col.Name).GetValue(NewValue, null);
- if (o.Where(lineKey).Count() == 0) //error!!!
- // 'object' does not contain a definition for 'Where' acception a first argument of type 'object' could be found (are you missing directive or an assembly reference?)
- NewValueSubCollection.Where(lineKey).Count() == 0
- NewValueSubCollection.Cast<dynamic>().Where(d => lineKey(d)).Count() == 0
- !NewValueSubCollection.Cast<dynamic>().Any(d => lineKey(d))
- class Program
- {
- static void Main(string[] args)
- {
- var list = new List<string>();
- IEnumerable<object> objects = list;
- Func<string, bool> func = s => s.Contains("x");
- list.Add("Test");
- list.Add("x");
- list.Add("mux");
- foreach (var item in objects.Cast<dynamic>().Where(d => func(d)))
- Console.WriteLine(item);
- Console.ReadKey();
- }
- }