如何解决错误无法从使用中推断出来。尝试明确指定类型参数?

时间:2016-09-09 07:17:51

标签: c# linq

static Func<T, object> CreateSelector<T>(IEnumerable<string> propertyNames)
{
    var sourceType = typeof(T);
    var parameter = Expression.Parameter(sourceType, "e");
    var properties = propertyNames.Select(name => Expression.PropertyOrField(parameter, name)).ToArray();
    var selector = Expression.Lambda<Func<T, object>>(
        Expression.Call(typeof(Tuple), "Create", properties.Select(p => p.Type).ToArray(), properties),
        parameter);
    return selector.Compile();
}
public static IEnumerable<Tuple<T, T>> Join<T>(this IEnumerable<T> left, IEnumerable<T> right, IEnumerable<string> propertyNames)
{
    var keySelector = CreateSelector<T>(propertyNames);
    return left.Join(right, keySelector, keySelector, Tuple.Create);
}
public static bool CompareLists<T1, T2>(IEnumerable<T1> lstProduct1, IEnumerable<T2> lstProduct2, List<DuplicateExpression> DuplicateExpression)
{
    string[] Fields = DuplicateExpression.Select(x => x.ExpressionName).ToArray();
    var JoinExp = lstProduct1.Join(lstProduct2, Fields);
    bool IsSuccess = true;// CompareTwoLists(lstProduct1, lstProduct2, (listProductx1, listProductx2) => JoinExp.Any());

    return IsSuccess;
}

当我编译上面的代码时;我在下面的行中收到错误

var JoinExp = lstProduct1.Join(lstProduct2, Fields);

错误是

  

错误1方法的类型参数   &#39; AP.Classes.ListComparison.Join(System.Collections.Generic.IEnumerable,   System.Collections.Generic.IEnumerable,   System.Collections.Generic.IEnumerable)&#39;无法推断   从用法。尝试指定类型参数   明确。 d:\车间\鸭\类\ DuplicateValidator.cs

如何解决此错误?我正在创建一个List比较工具。

1 个答案:

答案 0 :(得分:0)

提供的自定义Join方法不适用,因为它需要一个泛型类型参数,而您的方法有两个。

您可以使用提供的CreateSelector实现来实现自定义Join / GroupJoin扩展方法,类似于Enumerable类中相应的系统提供的方法,如下所示:

public static IEnumerable<TResult> Join<TOuter, TInner, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, IEnumerable<string> propertyNames, Func<TOuter, TInner, TResult> resultSelector)
{
    return outer.Join(inner, CreateSelector<TOuter>(propertyNames), CreateSelector<TInner>(propertyNames), resultSelector);
}

public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, IEnumerable<string> propertyNames, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
{
    return outer.GroupJoin(inner, CreateSelector<TOuter>(propertyNames), CreateSelector<TInner>(propertyNames), resultSelector);
}

然后,您可以使用上述自定义GroupJoin来有效地实施您的方法:

public static bool CompareLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, List<DuplicateExpression> DuplicateExpression)
{
    var fields = DuplicateExpression.Select(x => x.ExpressionName).ToArray();
    return list1.GroupJoin(list2, fields, (x, match) => match).All(match => match.Any())
        && list2.GroupJoin(list1, fields, (x, match) => match).All(match => match.Any());
}