获取不同的列表值 [英] Get distinct list values

查看:72
本文介绍了获取不同的列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想从项目对象的列表,其中包含不同的对象另一个列表以获得一个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 to Distinct
  • override Equals and GetHashCode on Project

有也很喜欢 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆