-1

I have a base class Posts and Notifications, Notes and Photos inherit from Posts. How can I a single list with all inherited objects from Posts in a single 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();

The above of course returns notes only.

Thanks in advance.

4

1 回答 1

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();
于 2013-10-27T21:37:25.160 回答