我有一个基类Posts
和Notifications
,Notes
和Photos
继承自Posts
。如何在单个List<Post>
中使用帖子中的所有继承对象的单个列表。
var notes = posts.OfType<Note>();
var photos = posts.OfType<Photo>();
var notifications = posts.OfType<Notification>(); ;
return (from n in notes
select new Stream()
{
id = n.post_id,
value = n.value,
timestamp = n.timestamp,
type = "note"
}).ToList();
上述内容当然仅返回说明。
提前致谢。
答案 0 :(得分:0)
您已经拥有从Posts
继承的对象列表:
var notes = posts.OfType<Note>();
var photos = posts.OfType<Photo>();
var notifications = posts.OfType<Notification>();
按如下方式列出Posts
。
List<Posts> posts = new List<Posts>();
并添加Posts
//posts.Add(new Note());
//posts.Add(new Notification());
//posts.Add(new Photo());
posts.AddRange(notes);
posts.AddRange(photos);
posts.AddRange(notifications);
// do the projection into Stream
return (from n in posts
select new Stream()
{
id = n.post_id,
value = n.value,
timestamp = n.timestamp,
type = "note"
}).ToList();