我有两个数组.例如:
int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};
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) 我收到了这个警告,但无法弄清楚问题......
CodeContracts:警告:布尔条件d1.Count!= d2.Count始终求值为常量值.如果它(或它的否定)出现在源代码中,您可能会有一些死代码或冗余检查
代码如下:
public static bool DictionaryEquals<TKey, TValue>(IDictionary<TKey, TValue> d1, IDictionary<TKey, TValue> d2)
{
if (d1 == d2) return true;
if (d1 == null || d2 == null) return false;
if (d1.Count != d2.Count) return false; // <-- warning here
// Equality check goes here
return true;
}
Run Code Online (Sandbox Code Playgroud)
该// Equality check goes here部分可以按原样,或由适当的实现替换,我仍然得到相同的警告.
嗨我有两个下一个类型的词典:
SortedDictionary<string, ClusterPatternCommonMetadata> PatternMetaData { get; set; }
Run Code Online (Sandbox Code Playgroud)
ClusterPatternCommonMetadata对象如下所示:
int ChunkQuantity { get; set; }
SortedDictionary<int, int> ChunkOccurrences { get; set; }
Run Code Online (Sandbox Code Playgroud)
首先,我需要找到两个字典中存在的PatternMetaData键的方法.我发现这样:
List<string> commonKeysString=
vector.PatternMetaData.Keys.Intersect(currentFindingVector.PatternMetaData.Keys)
Run Code Online (Sandbox Code Playgroud)
然后我需要找到已创建密钥的常用值...
是否有快速方式(lambda,linq等)才能进行此类操作
谢谢
我刚开始经历"破解编码面试"并针对此问题提供以下解决方案:
public static bool isAnagram(String s, String t)
{
if (s == "" || t == "") return false;
else if (s.Length != t.Length) return false;
int[] letters = new int[256];
char[] s_array = s.ToCharArray();
foreach(char c in s_array)
{
letters[c]++;
}
for (int i = 0; i < t.Length; i++)
{
int c = t[i];
if (--letters[c] < 0)
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
这几乎是本书的逐字解决方案,仅限于C#,而不是Java,还有一些额外的nullcheck.我还使用LINQ解决了这个问题,但想要一个不涉及排序的附加解决方案.
这种方法可以变得更优雅吗?代码工作正常,我只是想知道是否有更优雅或更好的解决方案.谢谢!!