在Python中是否有与KeyedCollection等效的东西,即元素拥有(或动态生成)自己的键的集合?
即这里的目标是避免将密钥存储在两个地方,因此字典不太理想(因此问题).
我想使用KeyedCollection来存储针对字符串键值的类.我有以下代码:
public class MyClass
{
public string Key;
public string Test;
}
public class MyCollection : KeyedCollection<string, MyClass>
{
public MyCollection() : base()
{
}
protected override String GetKeyForItem(MyClass cls)
{
return cls.Key;
}
}
class Program
{
static void Main(string[] args)
{
MyCollection col = new MyCollection();
col.Add(new MyClass()); // Here is want to specify the string Key Value
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这里我做错了什么?我在哪里指定键值,以便我可以通过它检索?
我正在寻找一种与泛型字典的Keys属性(类型为KeyCollection)一样高效的方法.
使用Linq select语句可以工作,但每次请求密钥时它都会迭代整个集合,而我相信密钥可能已经在内部存储.
目前我的GenericKeyedCollection类看起来像这样:
public class GenericKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem> {
private Func<TItem, TKey> getKeyFunc;
protected override TKey GetKeyForItem(TItem item) {
return getKeyFunc(item);
}
public GenericKeyedCollection(Func<TItem, TKey> getKeyFunc) {
this.getKeyFunc = getKeyFunc;
}
public List<TKey> Keys {
get {
return this.Select(i => this.GetKeyForItem(i)).ToList();
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:感谢您的回答,我将使用以下属性而不是使用Linq进行迭代.
public ICollection<TKey> Keys {
get {
if (this.Dictionary != null) {
return this.Dictionary.Keys;
}
else {
return new Collection<TKey>(this.Select(this.GetKeyForItem).ToArray());
}
}
}
Run Code Online (Sandbox Code Playgroud) 我想创建一个迭代键控集合的方法.我想确保我的方法支持任何扩展的集合的迭代KeyedCollection<string, Collection<string>>
这是方法:
public void IterateCollection(KeyedCollection<string, Collection<string>> items)
{
foreach (??? item in items)
{
Console.WriteLine("Key: " + item.Key);
Console.WriteLine("Value: " + item.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
它显然不起作用,因为我不知道哪种类型应该替换循环中的问号.我不能简单地放object或var因为我需要稍后在循环体中调用Key和Value属性.我在寻找什么类型的?谢谢.
我认为这是我们遇到的常见问题。
class Person
{
public string place;
public string name;
public Person(string place, string name)
{
this.place = place;
this.name = name;
}
public bool Equals(Person other)
{
if (ReferenceEquals(null, other))
return false;
return name == other.name;
}
public override bool Equals(object obj)
{
return Equals(obj as Person);
}
public override int GetHashCode()
{
return name.GetHashCode();
}
public override string ToString()
{
return place + " - " + name;
}
}
Run Code Online (Sandbox Code Playgroud)
说我有这门课。我可以实现KeyedCollection这样的:
class Collection : KeyedCollection<string, Person> …Run Code Online (Sandbox Code Playgroud)