Alvin
Alvin

Reputation: 8499

Cast a List of object to another List

I have two model class:

public class SalesItem
{
   public string ProductName { get; set; }
   public double UnitPrice { get; set; }
   public int Quantity { get; set; }
}

public class ProductItem : INotifyPropertyChanged
{
   public string ProductName { get; set; }
   public double UnitPrice { get; set; } 
}

I have a list of SalesItem, List<ProductItem> products, how can I cast it to List<SalesItem> sales


EDITED

List<ProductItem> salesList = new List<ProductItem>();
List<SalesItem> salesItem = salesList.Cast<SalesItem>();

Error:

Connot implicitly convert type 'System.Collections.Generic.IEnumerable<Model.SalesItem>' to 'System.Collections.Generic.List<Model.SalesItem>'. An explicit conversion exists (are you missing a cast?

Upvotes: 1

Views: 318

Answers (4)

Ran
Ran

Reputation: 6159

You would need to change SalesItem to inherit from ProductItem, and then you can use LINQ, like that:

List<ProductItem> products;
IEnumerable<SalesItem> salesItems = products.Cast<SalesItem>();

or

List<SalesItem> salesItems = products.Cast<SalesItem>().ToList();

Don't forget to ensure you have the following in the file, for the Cast extension method to be available:

using System.Linq;

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Tried and tested

Include namespace

using System.Linq;

and then

List<ProductItem> yourProductlist = new List<ProductItem>();

yourProductlist.Add(new ProductItem() { ProductName = "A", UnitPrice = 50 });
yourProductlist.Add(new ProductItem() { ProductName = "B", UnitPrice = 150 });

List<SalesItem> yourSaleslist = yourProductlist.Select(x => 
                           new SalesItem() { ProductName = x.ProductName, 
                                             UnitPrice = x.UnitPrice }).ToList();

See it working

enter image description here

Casting will work if ProductItem is inherited from SalesItem class

Upvotes: 2

keyboardP
keyboardP

Reputation: 69372

Here you can define what the value of defaultQuantity is, because it doesn't exist in ProductItem.

List<SalesItem> sales = products.ConvertAll(x => new SalesItem() {
                            ProductName = x.ProductName,
                            Quantity = defaultQuantity, 
                            UnitPrice = x.UnitPrice  
                        });

Upvotes: 1

nickolayratchev
nickolayratchev

Reputation: 1206

In the example you have given, you cannot cast between these two types because they have nothing in common with each other. The right way to do it would be to have a baseItem class and then a derivedItem class that inherits from baseItem. Then you can do:

List<baseItem> baseList;
List<derivedItem> derivedList = baseList.Cast<derivedItem>();

This is usually referred to as downcasting, and is often an indicator of an improper hierarchy in your code, so I suggest limiting its usage.

Upvotes: 2

Related Questions