gpt4 book ai didi

c# - 使用 HashSet C# 选择项目

转载 作者:行者123 更新时间:2023-11-30 20:03:34 25 4
gpt4 key购买 nike

我有一个哈希集。是否有一种方法可以利用 IEqualityComparer 检索您传入满足 IEqualityComparer 中定义的 equals 方法的对象的项目?

这可能会解释得更清楚一些。

    public class Program
{
public static void Main()
{
HashSet<Class1> set = new HashSet<Class1>(new Class1Comparer());
set.Add( new Class1() { MyProperty1PK = 1, MyProperty2 = 1});
set.Add( new Class1() { MyProperty1PK = 2, MyProperty2 = 2});

if (set.Contains(new Class1() { MyProperty1PK = 1 }))
Console.WriteLine("Contains the object");

//is there a better way of doing this, using the comparer?
// it clearly needs to use the comparer to determine if it's in the hash set.
Class1 variable = set.Where(e => e.MyProperty1PK == 1).FirstOrDefault();

if(variable != null)
Console.WriteLine("Contains the object");
}
}

class Class1
{
public int MyProperty1PK { get; set; }
public int MyProperty2 { get; set; }
}

class Class1Comparer : IEqualityComparer<Class1>
{
public bool Equals(Class1 x, Class1 y)
{
return x.MyProperty1PK == y.MyProperty1PK;
}

public int GetHashCode(Class1 obj)
{
return obj.MyProperty1PK;
}
}

最佳答案

如果您想根据单个属性检索 项目,您可能需要使用 Dictionary<T,U>而不是哈希集。然后,您可以使用 MyProperty1PK 将项目放入字典中。作为关键。

你的查询就变得简单了:

Class1 variable;
if (!dictionary.TryGetValue(1, out variable)
{
// class wasn't in dictionary
}

鉴于您已经在使用仅使用此值作为唯一性标准的比较器进行存储,因此仅将该属性用作字典中的键确实没有任何缺点。

关于c# - 使用 HashSet C# 选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com