This may seem silly, but all the examples I\'ve found for using Except
in linq use two lists or arrays of only strings or integers and filters them based on the
public static class ExceptByProperty
{
public static List ExceptBYProperty(this List list, List list2, Expression> propertyLambda)
{
Type type = typeof(T);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
Func func = propertyLambda.Compile();
var ids = list2.Select(x => func(x)).ToArray();
return list.Where(i => !ids.Contains(((TProperty)propInfo.GetValue(i, null)))).ToList();
}
}
public class testClass
{
public int ID { get; set; }
public string Name { get; set; }
}
For Test this:
List a = new List();
List b = new List();
a.Add(new testClass() { ID = 1 });
a.Add(new testClass() { ID = 2 });
a.Add(new testClass() { ID = 3 });
a.Add(new testClass() { ID = 4 });
a.Add(new testClass() { ID = 5 });
b.Add(new testClass() { ID = 3 });
b.Add(new testClass() { ID = 5 });
a.Select(x => x.ID);
var items = a.ExceptBYProperty(b, u => u.ID);