我之前从未真正这样做过,所以我希望有人可以告诉我正确实现我的类的Except()和GetHashCode()的重写.
我正在尝试修改类,以便我可以使用LINQ Except()方法.
public class RecommendationDTO{public Guid RecommendationId { get; set; }
public Guid ProfileId { get; set; }
public Guid ReferenceId { get; set; }
public int TypeId { get; set; }
public IList<TagDTO> Tags { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsActive { get; set; }
public object ReferencedObject { get; set; }
public bool IsSystemRecommendation { get; set; }
public int VisibilityScore { get; …Run Code Online (Sandbox Code Playgroud) 我只是想知道为什么该语言的设计者决定在匿名类型上实现Equals,类似于Equals值类型.这不是误导吗?
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void ProofThatAnonymousTypesEqualsComparesBackingFields()
{
var personOne = new { Name = "Pawe?", Age = 18 };
var personTwo = new { Name = "Pawe?", Age = 18 };
Console.WriteLine(personOne == personTwo); // false
Console.WriteLine(personOne.Equals(personTwo)); // true
Console.WriteLine(Object.ReferenceEquals(personOne, personTwo)); // false
var personaOne = new Person { Name = "Pawe?", Age = 11 };
var personaTwo = new …Run Code Online (Sandbox Code Playgroud) 我想在C#中将两个字典与作为键a string和值列表进行比较int.我假设两个字典在它们都具有相同的键时是相等的,并且对于每个键而言,它们是具有相同整数的列表(两者不一定是相同的顺序).
我使用了这个和这个相关问题的答案,但是我的测试套件都没有通过测试功能DoesOrderKeysMatter和DoesOrderValuesMatter.
我的测试套件:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
namespace UnitTestProject1
{
[TestClass]
public class ProvideReportTests
{
[TestMethod]
public void AreSameDictionariesEqual()
{
// arrange
Dictionary<string, List<int>> dict1 = new Dictionary<string, List<int>>();
List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);
dict1.Add("a", list1);
List<int> list2 = new List<int>();
list2.Add(3);
list2.Add(4);
dict1.Add("b", list2);
// act
bool dictsAreEqual = false;
dictsAreEqual = AreDictionariesEqual(dict1, dict1);
// assert
Assert.IsTrue(dictsAreEqual, "Dictionaries are not equal"); …Run Code Online (Sandbox Code Playgroud) 我有一个字典,我将其与另一个字典进行比较(变量类型为IDictionary).执行d1.Equals(d2)会产生错误.在下面编写自己的代码会产生真实.两者都是System.Collections.Generic.Dictionary.我缺少的东西或根本Dictionary没有一个Equals是比较键/值执行?
private static bool DictEquals<K, V>(IDictionary<K, V> d1, IDictionary<K, V> d2)
{
if (d1.Count != d2.Count)
return false;
foreach (KeyValuePair<K, V> pair in d1)
{
if (!d2.ContainsKey(pair.Key))
return false;
if (!Equals(d2[pair.Key], pair.Value))
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)