在通用方法中传递/指定属性?

use*_*406 8 .net c# generics func

我试图将我写的一些代码移动到更通用的方法.虽然方法较长,但我遇到问题的部分如下:

public static void Test()

{    
           MyObjectType[] list1 = ListMyObjectTypeMethod1();
            MyObjectType[] list2 = ListMyObjectTypeMethod2();

            List<MyObjectType> linqAblelist1 = new List<MyObjectType>(list1);
            List<MyObjectType> linqAblelist2 = new List<MyObjectType>(list2);

            IEnumerable<MyObjectType> toBeAdded = linqAblelist1.Where(x => linqAblelist2.All(y => y.Property1 != x.Property1));
            IEnumerable<MyObjectType> toBeDeleted = linqAblelist2.Where(a => linqAblelist1.All(b => b.Property1 != a.Property1));

}
Run Code Online (Sandbox Code Playgroud)

我试图为MyObjectType传递一个泛型类型,但我在哪里[如何在这里设置属性?]如何在方法的参数中指定?

public static void Test<T>(T[] x, T[] y)
        {
            List<T> list1 = new List<T>(x);
            List<T> list2 = new List<T>(y);
            IEnumerable<T> toBeAdded = list1.Where(x => list2.All(y => y.[How To Set Property Here?] != x.[How To Set Property Here?]));
            IEnumerable<T> toBeDeleted = list2.Where(a => list1.All(b => b.[How To Set Property Here?])); != a.[How To Set Property Here?]));));

        }
Run Code Online (Sandbox Code Playgroud)

And*_*bel 11

通过选择酒店作为Func<T, TProperty>:

public static void Test<T, TProperty>(T[] x, T[] y, Func<T, TProperty> propertySelector)
    {
        List<T> list1 = new List<T>(x);
        List<T> list2 = new List<T>(y);
        IEnumerable<T> toBeAdded = list1.Where(x => list2.All(y => !propertySelector(y).Equals(propertySelector(x))));
        IEnumerable<T> toBeDeleted = list2.Where(a => !list1.All(b => propertySelector(b).Equals(propertySelector(a))));

    }
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过为以下内容指定lambda表达式来调用它propertySelector:

Test(someArray, someOtherArray, t => t.SomeProperty);
Run Code Online (Sandbox Code Playgroud)