日期:2014-05-20  浏览次数:20809 次

在一个列表中查找不在另外一个列表中的元素
C# code

rptProdct2.DataSource = (from p in plist
                    join s in shopcart on p.ProductID equals s.ID
                     where p.ProductID != s.ID
                     orderby p.NowPrice descending
                     select p).OrderBy(p => p.NowPrice).Take(10);
rptProdct2.DataBind();


为什么返回的是null呢?

------解决方案--------------------
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class ShopCart
    {
        public int ID { get; set; }
        public int Count { get; set; }
    }

    public class Product
    {
        public int ProductId { get; set; }
        public decimal Price { get; set; }
        public string ProductName { get; set; }
        public override string ToString()
        {
            return ProductName;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Product> productList = new List<Product>()
            {
                new Product(){ ProductId=1, Price=10, ProductName="商品1"},
                new Product(){ ProductId=2, Price=10, ProductName="商品2"},
                new Product(){ ProductId=3, Price=10, ProductName="商品3"},
                new Product(){ ProductId=4, Price=10, ProductName="商品4"}
            };

            List<ShopCart> shopCart = new List<ShopCart>() 
            {
                new ShopCart(){ ID=1, Count=10},
                new ShopCart(){ ID=2, Count=10}
            };

            var query = productList.Except(from x in shopCart select productList.Where(y => y.ProductId == x.ID).Single());
            query.ToList().ForEach(x => Console.WriteLine(x));

        }
    }

}