Alan2
Alan2

Reputation: 24572

Problems ordering my collection with LINQ

I have the following:

var cities = _cityRepository.GetPk(partitionKey);
var sortedCities = cities.OrderBy(item => item.RowKey.Substring(0, 4))
                         .ThenBy(item => item.ShortTitle);
return sortedCities;

Where cities is: ICollection<City>

This is giving me an error

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<Storage.Models.City>' to 'System.Collections.Generic.ICollection<Storage.Models.City>'. An explicit conversion exists (are you missing a cast?)

Can someone help me out with this. I thought I can just run LINQ to reorder.

Upvotes: 0

Views: 137

Answers (3)

Alex
Alex

Reputation: 35409

"Can't cast to specified type", call .ToList:

var sortedCities = cities.OrderBy(item => item.RowKey.Substring(0, 4))
                                  .ThenBy(item => item.ShortTitle).ToList();

Upvotes: 1

madd0
madd0

Reputation: 9323

Your method seems to expect a return value of type ICollection<Storage.Models.City> but you are returning an IOrderedEnumerable<Storage.Models.City> which is more generally a IEnumerable<Storage.Models.City>.

You can either change the return type of your method or convert your return value into something that is an ICollection such as a List with ToList().

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

add .ToList() at the end as below

var sortedCities = cities.OrderBy(item => item.RowKey.Substring(0, 4))
                         .ThenBy(item => item.ShortTitle).ToList();

probably your method has to return IOrderedEnumerable

Upvotes: 4

Related Questions