获取不同的列表值 [英] Get distinct list values
问题描述
我有,我想从项目对象的列表
,其中包含不同的对象另一个列表以获得一个C#应用程序。
i have a C# application in which i'd like to get from a List
of Project objects , another List which contains distinct objects.
我想这
List<Project> model = notre_admin.Get_List_Project_By_Expert(u.Id_user);
if (model != null) model = model.Distinct().ToList();
该列表模式仍然包含4个完全相同的对象项目
。
是什么原因呢?我该如何解决呢?
What is the reason of this? How can i fix it?
推荐答案
您需要定义相同的在这里。我猜你的意思是具有相同的内容,但不作为类的默认定义:默认的定义是是相同的实例
You need to define "identical" here. I'm guessing you mean "have the same contents", but that is not the default definition for classes: the default definition is "are the same instance".
如果你想相同的是指具有相同的内容,你有两个选择:
If you want "identical" to mean "have the same contents", you have two options:
- 编写自定义比较(
的IEqualityComparer&LT;项目&GT;
)和供应作为一个参数鲜明
- 覆盖
等于
和GetHash code
在项目
- write a custom comparer (
IEqualityComparer<Project>
) and supply that as a parameter toDistinct
- override
Equals
andGetHashCode
onProject
有也很喜欢 DistinctBy
自定义方法可用很多地方,如果身份可以通过一个单一的财产( ID来确定这是有用的
,通常情况下) - 不是在BCL,虽然。但是,例如:
There are also custom methods like DistinctBy
that are available lots of places, which is useful if identity can be determined by a single property (Id
, typically) - not in the BCL, though. But for example:
if (model != null) model = model.DistinctBy(x => x.Id).ToList();
使用,例如:
public static IEnumerable<TItem>
DistinctBy<TItem, TValue>(this IEnumerable<TItem> items,
Func<TItem, TValue> selector)
{
var uniques = new HashSet<TValue>();
foreach(var item in items)
{
if(uniques.Add(selector(item))) yield return item;
}
}
这篇关于获取不同的列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!