使用LINQ获取继承对象的单个列表

时间:2013-10-27 21:34:34

标签: c# linq entity-framework

我有一个基类PostsNotificationsNotesPhotos继承自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();

上述内容当然仅返回说明。

提前致谢。

1 个答案:

答案 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();