创建自定义类在C#中一个独特的列表自定义、独特、列表

2023-09-03 05:15:59 作者:烂人

我收到了连接实体框架类型的列表,并希望只从列表返回不同的值。我用下面的方法,但它不是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();
 
精彩推荐
图片推荐