使用SequenceEqual传递通用EquaityComparer

时间:2016-07-15 14:58:31

标签: c# linq generics lambda linq-expressions

我正在更新问题,更清楚:

我正在尝试构建一个用于过滤记录的LINQ表达式。

例如:

public string Name {get; set;}
public List<string> Score { get; set; }

 public Student(string name, List<string> list=null)
 {
     Name=name;
     Score=list;
 }

我有一份这些学生的名单:

    List<Student> listStudent = new List<Student>
              { new Student("Jane", new List<string>{"A","B"}),
                new Student("Joe", new List<string>{"B", "C"}),
                new Student("Jack")};

现在,我想只获得分数与给定列表匹配的学生:

List<string> scoresToCompare=new List<string>{"B", "C"};
var Result= listStudent.Where(x =>x.Score!=null ? scoresToCompare.SequenceEqual(x.Score,  new StringComparer<string>()): false)

我的StringComparer在比较时忽略了大小写:

class StringComparer<T> : IEqualityComparer<T>
{
    public bool Equals(T x, T y)
    {
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Ignore case when comparing.
        return x.ToString().Equals(y.ToString(), StringComparison.InvariantCultureIgnoreCase);
    }

    public int GetHashCode(T item)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(item, null)) return 0;

        //Get hash code for the Name field if it is not null.
        int hashCode = item == null ? 0 : item.GetHashCode();

        //Calculate the hash code for the product.
        return hashCode;
    }

}

现在,我不知道列表中的项目类型直到运行时,所以我试图构建一个表达式来实现相同的结果。

Type typeOfItemInList = listStudent.FirstOrDefault().GetType(); //Not the exact code, but thats how I get the type

如何使用stringComparer?

调用sequenceEqual方法
var callSequenceEqualMethodWithComparer= Expression.Call(typeof(System.Linq.Enumerable), "SequenceEqual", new Type[] typeOfItemsInList }, new Expression[] { listToCompare1,  listToCompare2, **stringComparer**});

最后我还需要做一个Expression.Condition来检查x.Score!= null是否通过以下方式避免了null异常:

Expression.Condition(Expression.NotEqual(expressionOfList1, Expression.Constant(null)), Expression.Convert(Expression.Call(callSequenceEqualMethodWithComparer, expressionOfList1, expressionOdList2), typeof(bool)), Expression.Default(typeof(bool)) );

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以通过调用Expression.New()创建一个创建对象的表达式。

要获取该类型,您可以使用typeof(StringComparer<>)获取StringComparer<T>的开放通用类型,然后在其上调用MakeGenericType()以获取已关闭的类型,例如{{1} }。

放在一起:

StringComparer<string>