使用 LINQ 获取继承对象的单个列表
本文关键字:单个 列表 对象 继承 LINQ 获取 使用 | 更新日期: 2023-09-27 18:37:00
我有一个基类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();
当然,以上内容仅返回注释。
提前谢谢。
您已经有一个从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();