I'm searching more than 10 hours.
There are 10 classes and 1 datagrid in other window
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:
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?
Note: I wont use class1 or class2 or class3
Linq extensions are available for generic enumerables ( IEnumerable<>
), IList
is basically a IEnumerable
, so the extensions will no be available for a 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:
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:
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:
interface INamedObject
{
string Name { get; }
}
var items = datagrid1.ItemsSource as IEnumerable<INamedObject>;
datagrid1.ItemsSource = items.Where(a => a.Contains("text"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.