0

I have the below linq currently working, but what I would really like is to return an ICollection<SexyPeopleVM> instead of a list. But I can't get my head around the syntax and other alternative I've tried have failed at runtime.

Is this possible? How can I achieve this?

var o = from s in sexyPeople
                    select new SexyPeopleVM()
                    {
                        id = s.ID,
                        title = s.Title,
                        views = s.Views,
                        url = s.GetFullyQualifiedURL(),
                        friendlyDate = s.DateCreated.AsShortFriendly()
                    };
            List<SexyPeopleVM> list = o.ToList();
            return list;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
williamsandonz
  • 15,864
  • 23
  • 100
  • 186

3 Answers3

7

List<T> implements ICollection<T>.
You don't need to do anything.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4

As SLaks said, he beat me posting, but I wanted to add, you can make your code a little cleaner also:

return (from s in sexyPeople
                    select new SexyPeopleVM()
                    {
                        id = s.ID,
                        title = s.Title,
                        views = s.Views,
                        url = s.GetFullyQualifiedURL(),
                        friendlyDate = s.DateCreated.AsShortFriendly()
                    }).ToList();

One other thing, get Resharper if you do not have it.

I now use

var list = new List<object>();

instead of:

List<object> list = new List<object>();

A good post as to why to use var.

This is just a coding style buy Resharper cleans up your code quite a bit.

I get in the habit and alot of other cleaner habits, like the two above, thanks to Resharper. I can't live without it now.

Community
  • 1
  • 1
ErocM
  • 4,505
  • 24
  • 94
  • 161
1

If you really want the ICollection specifically, just do

 return o.ToList() as ICollection<SexyPeopleVM>;
Nathan
  • 64
  • 3