我有一个自定义对象用作 Dictionary<CustomType, IrrelevantType>
中的键并且自定义对象包含一个名为 Id
的属性:
public class CustomType {
public int Id { get; set; }
}
我需要检查字典,看看是否存在 Id
的键。属性等于提供的值。例如在半伪中:
bool containsKey = dictionary.Contains(c => c.Key.Id == Id);
我通过智能感知尝试过的所有事情最终都得到了类似的结果:
bool containsKey = dictionary.SingleOrDefault(s => s.Key.Id == Id).Key.Id == Id;
在我看来这是相当多余的,因为我已经在谓词中执行了比较。
是否有一种简单、易于理解且简洁的方法来确定 Dictionary<CustomType, IrrelevantType>
是否存在?包含一个具有特定值的属性的键?
如果您愿意,可以使用下面的代码来测试您的答案:
public class CustomType {
public int Id { get; set; }
public CustomType(int id) => Id = id;
}
// Put this in the main method of a console app:
Dictionary<CustomType, int> testDictionary = new Dictionary<CustomType, int>();
testDictionary.Add(new CustomType(0), 0);
testDictionary.Add(new CustomType(1), 3);
testDictionary.Add(new CustomType(2), 5);
testDictionary.Add(new CustomType(4), 8);
for (int i = 0; i < 10; i++)
if (testDictionary.SingleOrDefault(s => s.Key.Id == i).Key.Id == i)
Console.WriteLine($"A key with id '{i}' exists.");
输出应该是:
A key with id '0' exists.
A key with id '1' exists.
A key with id '2' exists.
A key with id '4' exists.
最佳答案
bool containsKey = dictionary.Keys.Any(c => c.id == id);
虽然这是一个 O(n)
解决方案,但字典键访问通常是 O(1)
。
另一种方法是为字典提供自定义的 IEqualityComparer
,它提供基于 id 的相等比较和哈希函数:
class IdComparer : IEqualityComparer<YourType>
{
public bool Equals(YourType t1, YourType t2)
{
return t1.Id == t2.Id;
}
public int GetHashCode(YourType t)
{
return t.Id.GetHashCode();
}
}
var dictionary = new Dictionary<YourType, ValueType>(new IdComparer());
那么下面的操作是O(1)
:
bool containsKey = dictionary.ContainsKey(new YourType{ Id = id });
关于c# - 根据该键的属性确定字典是否包含该键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64615877/