【问题标题】:RadComboBoxItemCollection not wotrking with linqRadComboBoxItem 集合不适用于 linq
【发布时间】:2009-08-11 16:42:40
【问题描述】:

我正在创建一些扩展方法,但在使用 RadComboBoxItemCollection 时遇到了一些错误,RadComboBoxItemCollection 似乎实现了 IEnumerable 但 linq 一直给我错误提示:

"找不到实现 源类型的查询模式 'Telerik.Web.UI.RadComboBoxItemCollection'。 '哪里' 没有找到。考虑 明确指定的类型 范围变量‘myItem’。”

从此代码

public static bool ContainsValue(this RadComboBoxItemCollection myList, string value)
{
      bool matches = (from myItem in myList where myItem.Value == value select myItem).Count() > 0;
      return matches;
}

另一方面,RadListBoxItemCollection 工作得很好

public static bool ContainsValue(this IEnumerable<RadListBoxItem> myList, string value)
{
      bool matches = (from myItem in myList where myItem.Value == value select myItem).Count() > 0;
      return matches;
}

我尝试做 IEnumerable,这解决了 linq 错误,但我得到了这个错误

"实例参数:无法转换 从 'Telerik.Web.UI.RadComboBoxItemCollection' 到 'System.Collections.Generic.IEnumerable'"

【问题讨论】:

    标签: linq extension-methods telerik


    【解决方案1】:

    RadComboBoxItemCollection 实现了非通用 IEnumerable 接口(而不是做明智的事情并实现 IEnumerable),因此您的标准 LINQ 操作将不起作用。您必须先使用“Cast”扩展方法:

     var result = myList.Items.Cast<RadComboBoxItem>();
    

    现在你有了一个更有用的 IEnumerable,你可以用它来做各种美妙的事情:

    public static bool ContainsValue(this RadComboBoxItemCollection myList, string value)
    {
          return myList.Items.Cast<RadComboBoxItem>().Count(item => item.Value.Equals(value, StringComparison.Ordinal)) > 0;
    }
    

    但是,比我更有经验的人可能会谈论这种方法的性能;使用旧的(LINQ 之前的)方式而不是将每个对象强制转换为 RadComboBoxItem 可能会更好地提高性能:

    public static bool ContainsValue(this RadComboBoxItemCollection myList, string value)
    {
          foreach (var item in myList)
              if (item.Value.Equals(value, StringComparison.Ordinal))
                  return true;
    
          return false
    }
    

    【讨论】:

    • 你说得对,我使用 for 循环进行了类似的修复,Telerik 正在更新控件以修复此问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多