Filter Linq EXCEPT on properties

前端 未结 8 1315
南方客
南方客 2020-12-04 17:45

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

8条回答
  •  执笔经年
    2020-12-04 18:12

    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);
    

提交回复
热议问题