相关疑难解决方法(0)

字典<TKey,TValue>中的哈希码

我正在玩字典,偶然发现了下面的情景

public class MyObject
{
    public string I { get; set; }
    public string J { get; set; }
    public string K { get; set; }

    public override int GetHashCode()
    {
        int hashCode = (I+J+K).GetHashCode();
        Debugger.Log(9, "INFO", hashCode.ToString() + System.Environment.NewLine);
        return hashCode;
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyObject obj1 = new MyObject() { I = "Hello", J = "World" };
        MyObject obj2 = new MyObject() { I = "Hello", J = "World" };

        Dictionary<MyObject, string> …
Run Code Online (Sandbox Code Playgroud)

.net dictionary hashcode

2
推荐指数
1
解决办法
3019
查看次数

collections.Contains(T)方法

我正在使用a System.Collections.Generic,其中包含我编写的类的实例.

我已经读过collections .Contains方法使用object.Equals(),或者Equals()IEquatable接口中实现该方法.

我已经覆盖了对象方法,以及从界面实现.但是,Queue.Contains(instance)总是返回false.我究竟做错了什么?

例如...

class Foo : IEquatable<Foo>
{
    ...
    int fooField1;
    ...

    public override bool Equals(object obj)
    {
         Foo other = obj as Foo;
         bool isEqual = false;

         if (other.fooField1 == this.fooField1)
         { 
             isEqual = true;
         }

         return isEqual;         
    }

    public bool Equals(Foo other)
    {
         bool isEqual = false;

         if (other.fooField1 == this.fooField1)
         { 
             isEqual = true;
         }

         return isEqual;         
    }

}
...

void SomeFunction()
{
    Queue<Foo> …
Run Code Online (Sandbox Code Playgroud)

c# containers contains equals iequatable

2
推荐指数
1
解决办法
2720
查看次数

字典允许我插入重复的键

我已经创建了一些类,因此我可以使用一对字典作为键

public class RouteKey
{
    public Equip Equipment { get; set; }
    public Destiny Destiny { get; set; }

    public RouteKey() { }
    public RouteKey(Equip Equipment, Destiny Destiny) {
        this.Equipment = Equipment;
        this.Destiny = Destiny;
    }
}

public override bool Equals(object obj)
{
    if (obj == null) return false;

    if (this.GetType() != obj.GetType()) return false;

    RouteKey rk = (RouteKey)obj;

    // use this pattern to compare reference members
    if (!Object.Equals(Equipment, rk.Equipment)) return false;

    // use this pattern to compare value members …
Run Code Online (Sandbox Code Playgroud)

c# dictionary

2
推荐指数
1
解决办法
1596
查看次数

避免在数据库中添加重复项的最佳方法

我有一个包含三列的SQL Server表:

表格1

col1 int
col2 int
col3 string
Run Code Online (Sandbox Code Playgroud)

我为所有三列定义了一个唯一约束 (col1, col2, col3)

现在,我有一个.csv文件,我想在此表中添加记录,*.csv文件可以有重复记录.

我在上面的场景中搜索了各种避免重复的选项.以下是适合我的三个选项.请看一下并提出一些关于每种方法的优点/缺点的想法,以便我可以选择最好的方法.

选项1 :

首先避免重复,即从csv文件向列表添加对象时.我用过HashSet<T>了这个并覆盖了类型T下面的方法:

public override int GetHashCode()
{
    return col1.GetHashCode() + col2.GetHashCode() + col3.GetHashCode();
}

public override bool Equals(object obj)
{
    var other = obj as T;
    if (other == null)
    {
        return false;
    }
    return col1 == other.col1
        && col2 == other.col2
        && col3 == other.col3;
}
Run Code Online (Sandbox Code Playgroud)

选项#2

List<T>代替HashSet<T>.

添加所有对象后删除重复项 List<T>

    List<T> distinctObjects = allObjects
        .GroupBy(x => new …
Run Code Online (Sandbox Code Playgroud)

c# sql-server hashset

2
推荐指数
1
解决办法
1684
查看次数

IEquatable不会调用Equals方法

嗯,我正面临IEquatable(C#)的问题.正如您在下面的代码中看到的,我得到了一个我实现IEquatable的类,但它的"Equals"方法无法实现.我的目标是:我的数据库中有一个日期时间列,我想区分日期,而不是考虑"时间"部分.

例如:12-01-2014 23:14将等于12-01-2014 18:00.

namespace MyNamespace
{
    public class MyRepository
    {
        public void MyMethod(int id)
        {
            var x = (from t in context.MyTable
                     where t.id == id
                     select new MyClassDatetime()
                     {
                         Dates = v.Date
                     }).Distinct().ToList();
        }
    }


public class MyClassDatetime : IEquatable<MyClassDatetime>
{
    public DateTime? Dates { get; set; }

    public bool Equals(MyClassDatetime other)
    {
        if (other == null) return false;
        return (this.Dates.HasValue ? this.Dates.Value.ToShortDateString().Equals(other.Dates.Value.ToShortDateString()) : false);
    }

    public override bool Equals(object other)
    {
        return this.Equals(other as MyClassDatetime );
    } …
Run Code Online (Sandbox Code Playgroud)

c# datetime entity-framework distinct iequatable

2
推荐指数
1
解决办法
460
查看次数

C#中的Dictionary.ContainsKey()没有在Dictionary中找到一个键

我正在尝试为特权/权限编写一个类.

我试图在C#中使用二进制基本权限系统.

我得到它,我相信它应该工作.但是,它没有按预期工作.

之后,我通过我的代码逐步完成,我可以在方法中看到一个问题,_mapPermissions该行if (dic.ContainsKey(vv))每次都返回false.

关键是一个类的实例具有2倍的值(即secionName,KeyIndex)

这是我的全班

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;

namespace POS
{
    class Roles
    {

        private Dictionary<PermissionsKey, int> systemPermissions = new Dictionary<PermissionsKey, int>();
        private Dictionary<PermissionsKey, int> userPermissions = new Dictionary<PermissionsKey, int>();

        public Roles()
        {
            this._getSystemPrivleges();
            this._getUserPrivleges();

            this._display(systemPermissions);
            this._display(userPermissions);

        }

        public bool hasAccess(string sectionName, string[] keys)
        {

            if (    this.systemPermissions.Count == 0
                 || this.userPermissions.Count == 0
                 || keys.Count() == 0
                 || String.IsNullOrEmpty(sectionName) 
             ) …
Run Code Online (Sandbox Code Playgroud)

c# authentication permissions dictionary user-permissions

2
推荐指数
1
解决办法
2304
查看次数

使用Dictionary和HashSet的GetHashCode方法

我有一个关于Dictionary和HashSet如何在C#中工作的问题.根据我的理解,GetHashCode用于哈希表以确定密钥唯一性.

在以下MSDN页面上,它指出:

哈希码是一个数值,用于插入和标识基于散列的集合中的对象,例如Dictionary类,Hashtable类或从DictionaryBase类派生的类型.

链接: MSDN Object.GetHashCode

如果是这种情况,为什么当包含与car1相同的哈希码时,ContainsKey和Contains会为car2返回false?如果我的理解是正确的,如果MSDN说的是正确的,那么两个都不应该返回真的吗?

class Program
{
    static void Main(string[] args)
    {            
        // Create a Dictionary and HashSet
        Dictionary<Car, int> carDictionary = new Dictionary<Car, int>();
        HashSet<Car> carSet = new HashSet<Car>();

        // Create 3 Cars (2 generic and 1 Civic)
        Car car1 = new Car();
        Car car2 = new Car();
        Car car3 = new Civic();

        // Test hash values
        int test1 = car1.GetHashCode(); // 22008501
        int test2 = car2.GetHashCode(); // 22008501
        int test3 = car3.GetHashCode(); // 12048305


        // …
Run Code Online (Sandbox Code Playgroud)

.net c# dictionary hashset

2
推荐指数
1
解决办法
1530
查看次数

如何覆盖没有任何数字作为字段的GetHashCode()?

所有资源显示如何覆盖Equals(object)GetHashCode()使用数字字段来实现该GetHashCode()方法:

实现Equals方法
Equals和GetHashCode的最佳策略是什么?
为什么在重写Equals方法时重写GetHashCode很重要?

但是,在我的课上,我没有任何数字字段.它是树中的节点,引用其父节点,子节点和接口作为数据:

public class Node
{
    private IInterface myInterface;
    private Node parent;
    private List<Node> children = new List<Node>();

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }
        var node = (Node)obj;
        return myInterface == node.myInterface;
    }

    public override int GetHashCode()
    {
        ???
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该用什么设置哈希码?

c# equality hashcode iequalitycomparer gethashcode

1
推荐指数
1
解决办法
318
查看次数

GetHashCode 用于保存字符串字段的类型

我有这个类,在那里我覆盖了 Object Equals:

public class Foo
{
    public string string1 { get; set; }

    public string string2 { get; set; }

    public string string3 { get; set; }

    public override bool Equals(object other)
    {
        if (!(other is Foo)) return false;
        Foo otherFoo = (other as Foo);

        return otherFoo.string1 == string1 && otherFoo.string2 == string2 && otherFoo.string3 == string3;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个警告“覆盖 object.equals 但不覆盖 object.gethashcode”,我理解覆盖 GetHashCode 的必要性,以便我的类型根据可散列类型进行操作。

据我研究,为了使此代码唯一,通常使用 XOR 运算符,或者涉及素数乘法。所以,根据我的消息来源,来源1源2我正在考虑我的GesHashCode覆盖方法这两个选项。

1:

public override int GetHashCode() {
        return …
Run Code Online (Sandbox Code Playgroud)

c# equality gethashcode

1
推荐指数
1
解决办法
36
查看次数

c#List <T> .Contains()方法返回False

在下面的代码块中,我希望dictCars包含:{Chevy:Camaro,Dodge:Charger}

但是,dictCars回来了.因为每次调用此行都返回false:

if(myCars.Contains(new Car(Convert.ToInt64(strCar.Split(':')[1]),strCar.Split(':')[2])))
Run Code Online (Sandbox Code Playgroud)

代码块:

public class Car
{
    public long CarID { get; set; }

    public string CarName { get; set; }

    public Car(long CarID, string CarName)
    {
        this.CarID = CarID;
        this.CarName = CarName;
    }
}

List<Car> myCars = new List<Car>();
myCars.Add(new Car(0,"Pinto"));
myCars.Add(new Car(2,"Camaro"));
myCars.Add(new Car(3,"Charger"));

Dictionary<string, string> dictCars = new Dictionary<string, string>();
string strCars = "Ford:1:Mustang,Chevy:2:Camaro,Dodge:3:Charger";
String[] arrCars = strCars.Split(',');
foreach (string strCar in arrCars)
{
    if(myCars.Contains(new Car(Convert.ToInt64(strCar.Split(':')[1]),strCar.Split(':')[2])))
    {
        if (!dictCars.ContainsKey(strCar.Split(':')[0]))
        {
            dictCars.Add(strCar.Split(':')[0], strCar.Split(':')[2]);
        }
    }
} …
Run Code Online (Sandbox Code Playgroud)

c# asp.net

0
推荐指数
2
解决办法
5411
查看次数

C#:如何为以下类型的类实现GetHashCode?

我有一个类似于以下的课程:

class Abc
{
     public string A {get;set;}
     public string B {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

对于平等的标准是,如果任何的AB匹配类的两个对象Abc应该匹配。

public override bool Equals (Abc obj)
{
      if (obj.A == A || obj.B == B)
           return true;
      else return false;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以让我知道GetHashCode在这种情况下什么样的函数会给出相等的值。

因为两个AB字段可能有也可能没有相同的值。

c#

0
推荐指数
1
解决办法
44
查看次数