1

编辑:以下代码有效!(我注释掉,构建,然后取消注释并且它起作用了)。

我有ObservableCollection一个ListBox. 我想仅根据显示名称选择其中一些项目,因为我不知道项目值。但是我得到一个转换错误(IEnumerable 到 ObservableCollection)。

ObservableCollection<ListBoxItem> unselectedcollection
    = new ObservableCollection<ListBoxItem>
        (dt.AsEnumerable()
           .Select(i => new ListBoxItem(i[ColumnNames.LISTNAMECOL].ToString(),
                                        i[ColumnNames.LISTVALUECOL].ToString())));

ObservableCollection<ListBoxItem> selectedcollection
    = new ObservableCollection<ListBoxItem>
        (from item in unselectedcollection.AsEnumerable()
         where (item.Name == "firstName"
                || item.Name == "secondName"
                || item.Name == "thirdName")
         select item);

我已经尝试了我能想到的各种铸造选项。我错过了什么?

4

2 回答 2

0

我无法解释如何或为什么,但我注释掉了这一部分,用空白列表填充它以继续测试。我刚回来并取消注释它以提供确切的错误消息(按照@nakiya的要求)并重建......

......它奏效了。

同样,我不知道如何或为什么,但至少我可以继续前进。

于 2013-07-01T03:55:36.167 回答
0

我在处理集合并将 Linq 结果传递给它们时遇到的一个常见问题是集合没有被枚举,而通过调用 ToList 来枚举它通常可以解决这个问题。我会试一试,看看它是否有帮助。

ObservableCollection<ListBoxItem> selectedcollection
  = new ObservableCollection<ListBoxItem>(
      unselectedcollection.AsEnumerable()
                          .Where(item => item.Name == "firstName"
                                         || item.Name == "secondName"
                                         || item.Name == "thirdName")
                          .ToList());
于 2013-07-01T03:45:26.610 回答