创建自定义类在C#中一个独特的列表 [英] Creating a distinct list of custom type in C#

查看:250
本文介绍了创建自定义类在C#中一个独特的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了连接实体框架类型的列表,并希望只从列表返回不同的值。我用下面的方法,但它不是uniquifying名单。有什么建议?

I receive a List of en entity framework type and want to only return the distinct values from the List. I'm using the following approach, however it's not uniquifying the list. Any suggestions?

参数:名单,其中,旗>标志

List<Flag> distinctFlags = flags.Distinct().ToList();

是标志的值如下:标识,标志,FlagValue。我能在这种情况下使用LINQ?

The values of Flag are as follows: ID, Flag, FlagValue. Could I use linq in this instance?

感谢。

推荐答案

假设标志是你的实体模型之一,您可以使用部分 并覆盖等于 GetHash code 。这还假定在你有一个编号属性在标志 用来唯一标识它。

Assuming Flag is one of your entity models, you could use a partial class and override Equals and GetHashCode. This also assumes that you have an Id property on on your Flag class which uniquely identities it.

//this namespace MUST match the namespace of your entity model.
namespace Your.Entity.Model.Namespace
{
    public partial class Flag
    {
        public override bool Equals(object obj)
        {
            var item = obj as Flag;

            if (item == null)
            {
                return false;
            }

            return this.Id.Equals(item.Id);
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }
    }
}

用法是这样

List<Flag> distinctFlags = allFlags.Distinct().ToList();

这篇关于创建自定义类在C#中一个独特的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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