【发布时间】:2014-04-06 18:01:00
【问题描述】:
我们有 6 个 ObservableCollection List<Parent> 中的 ObservableCollection<T>,它们都有不同类型的子类。
我们想要做的是使用一个通用方法来检索所有具有相同类型的对象,换句话说,检索一个包含所有<T> 孩子的列表。
这是我的源代码
类 A 和 B 是 Parent 的子类。
ObservableCollection<ManagerTemplate> ManagerListStack = new ObservableCollection<ManagerTemplate>(ManagerTemplates);
class ManagerTemplate
{
public Type _Type { get; set; }
public ObservableCollection<Parents> parentList {get;set;}
}
internal static List<ManagerTemplate> ManagerTemplates = new List<ManagerTemplate>()
{
new ManagerTemplate{ List= new ObservableCollection<Parent>(),Type=typeof(A)},
new ManagerTemplate{ List= new ObservableCollection<Parent>(),Type=typeof(B)}
};
public static List<T> Get<T>() where T : Parent
{
/*(ManagerListStack.Where(x => x._Type == typeof(T)).First().List.Cast<T>()).ToList(); -- TRY 1*/
/*(List<T>)(ManagerListStack.Where(x => x._Type == typeof(T)).First().List.Cast<T>())* -- TRY 2*/
return (ManagerListStack.Where(x => x._Type == typeof(T)).First().List.Cast<T>()).ToList();
}
使用
(ManagerListStack.Where(x => x._Type == typeof(T)).First().List as List<T>)
返回的列表不包含任何元素。我100%确定并且已经调试了列表,里面有元素。
使用
(List<T>)(ManagerListStack.Where(x => x._Type == typeof(T)).First().List.Cast<T>())
我收到错误消息“无法从父级转换为 A 或 B”
【问题讨论】:
-
我是否正确理解 ManagerTemplate 将始终持有单一类型 Parent 的单一 ObeservableCollection?
-
是的,正确的。每个 ManagerTemplate 内部都会有一个 ObserableCollection,其中包含相同类型的对象。
-
你的问题是什么?您似乎已经有了解决方案。
-
解决方案不起作用。
-
SelectManyto flatten 而不是OfTypeto select 可能会产生更易于阅读的代码...请注意,“解决方案不起作用”是对问题的错误解释 - 您应该先调试它看看究竟是什么不起作用 - 试图在一个语句中进行复杂的过滤并不是调查 LINQ 问题的最简单方法......