linq 去重复问题

fengxuemofa6 2012-08-23 10:47:02
return db.product.Where(t => t.p_type == type).Distinct().ToList();这样去除重复数据,没有效果,求教
...全文
7441 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
E次奥 2013-04-12
  • 打赏
  • 举报
回复
Distinct里边可以写参数的!
  • 打赏
  • 举报
回复
引用 3 楼 Chinajiyong 的回复:
db.product.Where(t => t.p_type == type).Distinct().ToList(); 这样不行???
ToList 了 是没有用的 直接VAR接收结果 然后在对象化,实在不可以 手动去除重复项,呵呵
fengxuemofa6 2012-08-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

return db.product.Select(t => t.p_type == type).Distinct().ToList();
[/Quote]我是个List<model.product>不让用select说是无法吧Bool转换为model.product
暖枫无敌 2012-08-23
  • 打赏
  • 举报
回复
return db.product.Select(t => t.p_type == type).Distinct().ToList();
宝_爸 2012-08-23
  • 打赏
  • 举报
回复
参考这个代码:


public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}

// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Product x, Product y)
{

//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;

//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;

//Check whether the products' properties are equal.
return x.Code == y.Code && x.Name == y.Name;
}

// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.

public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;

//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

//Get hash code for the Code field.
int hashProductCode = product.Code.GetHashCode();

//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}

}

Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 9 },
new Product { Name = "lemon", Code = 12 } };

//Exclude duplicates.

IEnumerable<Product> noduplicates =
products.Distinct(new ProductComparer());

foreach (var product in noduplicates)
Console.WriteLine(product.Name + " " + product.Code);

/*
This code produces the following output:
apple 9
orange 4
lemon 12
*/



代码来自msdn:
http://msdn.microsoft.com/en-us/library/bb338049
宝_爸 2012-08-23
  • 打赏
  • 举报
回复
或者用这个overload:

Enumerable.Distinct<TSource> Method (IEnumerable<TSource>, IEqualityComparer<TSource>)
宝_爸 2012-08-23
  • 打赏
  • 举报
回复
product要重载比较的运算符。
EnForGrass 2012-08-23
  • 打赏
  • 举报
回复
db.product.Where(t => t.p_type == type).Distinct().ToList();
这样不行???

8,494

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧