简体   繁体   English

WPF Datagrid.ItemsSource作为列表 <Anything> 并在Linq上使用

[英]WPF Datagrid.ItemsSource as List<Anything> and use on Linq

I'm searching more than 10 hours. 我搜索了10多个小时。

There are 10 classes and 1 datagrid in other window 在其他窗口中有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

I need to convert and use the return items in Linq: 我需要转换并使用Linq中的退货项目:

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

I'm using these. 我正在使用这些。 but not work 但不起作用

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

what things I should use instead ??? 我应该用什么东西代替? for support Linq? 寻求支持Linq?

Note: I wont use class1 or class2 or class3 注意:我不会使用class1或class2或class3

Linq extensions are available for generic enumerables ( IEnumerable<> ), IList is basically a IEnumerable , so the extensions will no be available for a IList . Linq扩展可用于通用枚举( IEnumerable<> ), IListIEnumerable ,因此这些扩展将IList用于IList

Things like datagrid1.ItemsSource as List<object> returns null because a List<DerivedClass> isn't a List<BaseClass> , you can read more in this questions: 由于List<DerivedClass>不是List<BaseClass> ,诸如datagrid1.ItemsSource as List<object>返回null ,您可以在以下问题中阅读更多内容:

You can solve your problem calling Cast<> extension (that is available for IEnumerable ), this extension project the enumerable to a new IEnumerable<> casting each element to the specified generic type: 您可以解决调用Cast <>扩展(可用于IEnumerable )的问题,此扩展将可枚举项目投影到新的IEnumerable<>将每个元素转换为指定的通用类型:

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

However, if you classes have a common class or interface and as IEnumerable<> is co-variant you try something like this: 但是,如果您的类具有公共类或接口,并且IEnumerable<>是协变的,则可以尝试如下操作:

interface INamedObject
{
    string Name { get; }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM