Edw*_*ard 6 c# linq collections
我经常遇到的一个问题是需要以这样的方式存储对象集合,以便我可以通过特定的字段/属性来检索它们,该字段/属性是该对象的唯一"索引".例如,我有一个Person对象,其name字段是唯一标识符,我希望能够从一些Person对象集合中检索Person其中name="Sax Russell".在Java中,我通常通过使用Map我真正想要的地方来实现这一点Set,并且总是使用对象的"索引"字段作为地图中的键,即peopleMap.add(myPerson.getName(), myPerson).我想在C#中用Dictionarys 做同样的事情,像这样:
class Person {
public string Name {get; set;}
public int Age {get; set;}
//...
}
Dictionary<string, Person> PersonProducerMethod() {
Dictionary<string, Person> people = new Dictionary<string, Person>();
//somehow produce Person instances...
people.add(myPerson.Name, myPerson);
//...
return people;
}
void PersonConsumerMethod(Dictionary<string, Person> people, List<string> names) {
foreach(var name in names) {
person = people[name];
//process person somehow...
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这看起来很笨拙,并且在Dictionary它的值和它的值之间引入了相当松散的耦合; 我隐含地依赖于每个Person字典制作者使用该Name属性作为存储每个字典的关键Person.除非我每次访问字典时都仔细检查,否则我无法保证元素at people["Sax Russell"]实际上是一个.PersonName="Sax Russell"
有没有办法明确确保我的Person对象集合是通过名称索引,使用自定义相等比较器和/或LINQ查询?查找保持恒定时间非常重要,这就是为什么我不能只使用List.Find或Enumerable.Where.我已经尝试使用a HashSet并使用相等比较器构建它,该比较器只比较Name它给出的对象的字段,但似乎没有任何方法可以Person使用它们的名称来检索对象.
我不确定是否有任何内置功能可以满足您的需求,但是没有什么可以阻止您自行包装指定密钥的字典并实现IList<Person>.这里的关键(没有双关语)是消费者无法访问基础字典,因此您可以确保密钥是准确的.
部分实现可能如下所示,请注意自定义索引器:
public partial class PersonCollection : IList<Person>
{
//the underlying dictionary
private Dictionary<string, Person> _dictionary;
public PersonCollection()
{
_dictionary = new Dictionary<string, Person>();
}
public void Add(Person p)
{
_dictionary.Add(p.Name, p);
}
public Person this[string name]
{
get
{
return _dictionary[name];
}
}
}
Run Code Online (Sandbox Code Playgroud)
作为附带奖励,您也可以在以后更改实施,而无需更改消耗代码.
您可以构建自己的由字典支持的集合来完成此任务。这个想法是存储一个委托,该委托接受一个 Person 并通过读取 Name 属性返回一个字符串。
这是此类集合的骨架解决方案:
public class PropertyMap<K,V> : ICollection<V> {
private readonly IDictionary<K,V> dict = new Dictionary<K,V>();
private readonly Func<V,K> key;
public PropertyMap(Func<V,K> key) {
this.key = key;
}
public void Add(V v) {
dict.Add(key(v));
}
// Implement other methods of ICollection
public this[K k] {
get { return dict[k]; }
set { dict[k] = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
以下是如何使用它:
PropertyMap<string,Person> mp = new PropertyMap<string,Person>(
p => p.Name
);
mp.Add(p1);
mp.Add(p2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3384 次 |
| 最近记录: |