简体   繁体   中英

Cast from list object to class in c#

I am new to linq and also c#. Here i am facing a problem that, i have to 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 i want to create an extension method that will sort all item in my shopping cart.

public static ShoppingCart Sort(this ShoppingCart cart)
{

    var sortedCart = from item in cart.Products
                     orderby item.Title ascending
                     select item;
    return sortedCart.ToList();
}

So the method will not allow me to return sortedCart.ToList() , because this contain List. How can i return shoppingCart? If anyone know please help me. Thanks

Create a new ShoppingCart instance and set its Products to be the sorted list you just produced:

return new ShoppingCart { Products = sortedCart.ToList() };

Of course this way the original cart will not be sorted; it's the new (duplicate) cart that will be. If you wanted to sort the original in-place, you should use List<T>.Sort on the original product collection and not LINQ:

cart.Products.Sort((x,y) => x.Title.CompareTo(y.Title));

You need a way to create a shopping cart from a list of products. You could either use your existing setter or a constructor:

public class ShoppingCart
{
    public ShoppingCart(List<Product> products)
    {
        this.Products = products;
    }
...
}

Then just return new ShoppingCart(sortedCart.ToList());

Why the need of the extension method?

Assuming that the List is already filled just.

shoppingCart.Products.OrderBy(x => x.Title);

or using the extension method

public static void Sort(this ShoppingCart cart)
{

    cart.Products = (from item in cart.Products
                     orderby item.Title ascending
                     select item).ToList();
}

or

public static void Sort(this ShoppingCart cart)
{  
    shoppingCart.Products.OrderBy(x => x.Title);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM