user1733271
user1733271

Reputation: 117

Reverse a list c#

I have inserted the EventData EntityList into a normal List and now I want to reverse it. But it gives the error "Cannot implicitly convert type 'void' to 'object'"

List<Entities.Notification> ProgramList = EventData.ToList();
ListViewEvents.DataSource = ProgramList.Reverse();
ListViewEvents.DataBind();

How do I reverse this list? Is it possible to directly reverse the EntityList as well?

Upvotes: 4

Views: 3403

Answers (3)

D Stanley
D Stanley

Reputation: 152521

The compiler is choosing the method List<T>.Reverse() instead of the Linq extension method Enumerable.Reverse<T>(this IEnumerable<T>).

Since List<T>.Reverse() modifies the list by reversing the elements in-place rather than returning a new list, you can either just call that as a separate step:

List<Entities.Notification> ProgramList = EventData.ToList();
ProgramList.Reverse();
ListViewEvents.DataSource = ProgramList;
ListViewEvents.DataBind();

or

List<Entities.Notification> ProgramList = EventData.ToList().Reverse();
ListViewEvents.DataSource = ProgramList;
ListViewEvents.DataBind();

or you can call AsEnumerable() instead of ToList() to bind to the extension method instead:

List<Entities.Notification> ProgramList = EventData.AsEnumerable();
ListViewEvents.DataSource = ProgramList.Reverse(); // returns a new IEnumerable
ListViewEvents.DataBind();

As a side note, the extension method may perform better that List<T>.Reverse since it returns an iterator that traverses the list in reverse order rather than physically reversing the order of items in the list.

Upvotes: 5

Brian Maupin
Brian Maupin

Reputation: 745

Reverse does the reversal in place and does not return anything. Instead do:

List<Entities.Notification> ProgramList = EventData.ToList();
ProgramList.Reverse();
ListViewEvents.DataSource = ProgramList;
ListViewEvents.DataBind();

Upvotes: 20

Khan
Khan

Reputation: 18142

The reverse method does not return a new List. Call it, then set the datasource.

List<Entities.Notification> ProgramList = EventData.ToList();
ProgramList.Reverse();
ListViewEvents.DataSource = ProgramList;
ListViewEvents.DataBind();

Upvotes: 5

Related Questions