【问题标题】:Dynamic Linq & ICompare动态 Linq 和 ICompare
【发布时间】:2012-09-03 06:38:49
【问题描述】:

我正在尝试利用 James McCormack 的指南来使用带有 Dynamic Linq 的自定义 IComparer。 - 见http://zootfroot.blogspot.co.uk/2009/10/dynamic-linq-orderby.html?showComment=1347276236930#c11348033278810583

我使用查询来拉回一个可枚举的字符串值:

.Select("fieldname").Distinct()

那就试试用

.OrderBy(item=>item.GetReflectedPropertyValue("fieldname"),new myComparer()) 

GetReflectedPropertyValue 是 James 定义为的辅助方法

public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}

但是得到错误“'System.Collections.Generic.IEnumerable'不包含'OrderBy'的定义和最佳扩展方法重载'System.Linq.Dynamic.DynamicQueryable.OrderBy(System.Linq.IQueryable, string , params object[])' 有一些无效参数"

有什么想法吗?我对此很陌生,只是想在我有时间真正经历并正确学习它之前让一些东西发挥作用。

【问题讨论】:

    标签: c# linq dynamic sql-order-by


    【解决方案1】:

    仅根据您发布的内容很难判断,因为OrderBy 的分辨率将取决于myConverter 的实现。但是,由于GetReflectedPropertyValue 返回stringmyConverter 必须实现IConverter<String> 才能与OrderBy 一起使用。如果它不存在,并且它实现了类似IComparer<MyItem> 的东西,那么编译器实际上是在寻找一个不存在的方法OrderBy(this IEnumerable<object>, Func<object,string>, IComparer<MyItem>) 并吐出那个错误。

    如果不清楚,请提供myConverter 的详细信息,我可以更具体。

    如果您使用的东西没有实现IComparer<T>,那么您可以用实现IComparable<string> 的东西包装IComparer,使其与Orderby 兼容。例如:

    public class MyStringComparer : IComparer<String>
    {
        readonly IComparer comparer = new MyComparer();
        public int Compare(string x, string y)
        {
            return comparer.Compare(x, y);
        }
    }
    

    【讨论】:

    • 感谢您的回复。我实际上正在使用这个比较器davekoelle.com/files/AlphanumComparator.cs,我认为这没问题,因为它期待一个通用对象?
    • 顺便说一句,当我尝试您的包装器时,我收到此消息“非泛型类型 'System.Collections.IComparer' 不能与类型参数一起使用” - 忽略这一点,意识到我没有包括 System.Collections.Generic
    • 是的,谈谈小学生的错误!现在可以了。谢谢你,非常感谢彼得的帮助。
    猜你喜欢
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    相关资源
    最近更新 更多