【问题标题】:WPF Datagrid.ItemsSource as List<Anything> and use on LinqWPF Datagrid.ItemsSource 作为 List<Anything> 并在 Linq 上使用
【发布时间】:2016-06-03 20:13:22
【问题描述】:

我搜索了 10 多个小时。

其他窗口有 10 个类和 1 个数据网格

datagrid1.ItemsSource = new List<class1>(); //+100 items in list
or
datagrid1.ItemsSource = new List<class2>(); //+100 items in list
or
datagrid1.ItemsSource = new List<class3>(); //+100 items in list

我需要在Linq中转换和使用退货项目:

var items = datagrid1.ItemsSource as List<???>;
datagrid1.ItemsSource = items.Where(a => a.GetType().GetProperty("Name").GetValue(a, null).ToString().Contains("text"));

我正在使用这些。但不工作

using System.Linq;

var items = datagrid1.ItemsSource as IList;
//Error CS1061  'IList' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'IList' could be found (are you missing a using directive or an assembly reference?)

var items = datagrid1.ItemsSource as List<dynamic>; // return null
var items = datagrid1.ItemsSource as List<object>; // return null

我应该改用什么东西???支持 Linq?

注意:我不会使用 class1 或 class2 或 class3

【问题讨论】:

  • datagrid1.ItemsSource.Cast&lt;object&gt;().Where(...)
  • 哇。这是我的回答。非常感谢。
  • 但是为什么 ItemsSource as List 返回 null 而 cast 不返回 null ?

标签: c# wpf linq datagrid itemssource


【解决方案1】:

Linq 扩展可用于通用枚举 (IEnumerable&lt;&gt;),IList 基本上是 IEnumerable,因此扩展不适用于 IList

datagrid1.ItemsSource as List&lt;object&gt; 之类的内容返回 null,因为 List&lt;DerivedClass&gt; 不是 List&lt;BaseClass&gt;,您可以在以下问题中阅读更多信息:

您可以通过调用Cast<> 扩展(可用于IEnumerable)来解决您的问题,此扩展将可枚举项目转换为新的IEnumerable&lt;&gt;,将每个元素转换为指定的泛型类型:

datagrid1.ItemsSource.Cast<object>().Where(...)

但是,如果你的类有一个通用的类或接口,并且 IEnumerable&lt;&gt; 是协变的,你可以试试这样:

interface INamedObject
{
    string Name { get; }
}

var items = datagrid1.ItemsSource as IEnumerable<INamedObject>;
datagrid1.ItemsSource = items.Where(a => a.Contains("text"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 2014-01-05
    • 1970-01-01
    • 2016-07-18
    • 2013-03-13
    相关资源
    最近更新 更多