如何使用linq添加“get all”方法

时间:2012-08-25 02:12:05

标签: c# asp.net asp.net-mvc linq entity-framework

我想在班上添加一个“get all”项目方法。使用lineCollection我可以看到(.find(),。findall(),. findindex())但我不认为这是我需要的东西?有什么帮助吗?

using System.Collections.Generic;
using System.Linq;

namespace SportsStore.Domain.Entities
{
    public class Cart
    {
        private readonly List<CartLine> lineCollection = new List<CartLine>();

        public IEnumerable<CartLine> Lines
        {
            get { return lineCollection; }
        }

        public void AddItem(Product product, int quantity)
        {
            CartLine line = lineCollection
                .Where(p => p.Product.ProductID == product.ProductID)
                .FirstOrDefault();

            if (line == null)
            {
                lineCollection.Add(new CartLine {Product = product, Quantity = quantity});
            }
            else
            {
                line.Quantity += quantity;
            }
        }

        public void RemoveLine(Product product)
        {
            lineCollection.RemoveAll(l => l.Product.ProductID == product.ProductID);
        }

        public decimal ComputeTotalValue()
        {
            return lineCollection.Sum(e => e.Product.Price*e.Quantity);
        }

        public void Clear()
        {
            lineCollection.Clear();
        }

    }

    public class CartLine
    {
        public Product Product { get; set; }
        public int Quantity { get; set; }
    }
}

1 个答案:

答案 0 :(得分:4)

lineCollection已经是一个列表。只需返回List即可获得所有元素。如果要对这些元素执行某些操作,可以使用foreach循环。如果需要将IQueryable转换为List,请使用.ToList()

相关问题