linq - Cast from list object to class in c# -


i new linq , c#. here facing problem that, have model class

public class product {     public int itemid { get; private set; }     public string title { get; set; }     public string description { get; set; }     public datetime auctionenddate { get; set; }     public int price { get; set; } }  public class shoppingcart {     public list<product> products { get; set; } } 

here want create extension method sort item in shopping cart.

public static shoppingcart sort(this shoppingcart cart) {      var sortedcart = item in cart.products                      orderby item.title ascending                      select item;     return sortedcart.tolist(); } 

so method not allow me return sortedcart.tolist(), because contain list. how can return shoppingcart? if know please me.

create new shoppingcart instance , set products sorted list produced:

return new shoppingcart { products = sortedcart.tolist() }; 

of course way original cart not sorted; it's new (duplicate) cart be. if wanted sort original in-place, should use list<t>.sort on original product collection , not linq:

cart.products.sort((x,y) => x.title.compareto(y.title)); 

Comments