相关疑难解决方法(0)

如果键不存在,则字典返回默认值

我发现自己现在经常在我的代码中使用当前模式

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

var somethingElse = dictionary.ContainsKey(key) ? dictionary[key] : new List<othertype>();
// Do work with the somethingelse variable
Run Code Online (Sandbox Code Playgroud)

或者有时候

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
    somethingElse = new List<othertype>();
}
Run Code Online (Sandbox Code Playgroud)

这两种方式都让人觉得很迂回.我真正想要的是这样的

dictionary.GetValueOrDefault(key)
Run Code Online (Sandbox Code Playgroud)

现在,我可以为字典类编写一个扩展方法来为我做这个,但我想我可能会遗漏已经存在的东西.那么,有没有办法以更简单的方式做到这一点,而无需在字典中编写扩展方法?

c# collections dictionary

216
推荐指数
4
解决办法
14万
查看次数

是否有一个IDictionary实现,在缺少键时,返回默认值而不是抛出?

如果缺少键,则Index into Dictionary会引发异常.是否有IDictionary的实现,而是返回默认值(T)?

我知道"TryGetValue"方法,但这不可能与linq一起使用.

这会有效地做我需要的吗?:

myDict.FirstOrDefault(a => a.Key == someKeyKalue);
Run Code Online (Sandbox Code Playgroud)

我认为它不会,因为我认为它将迭代键而不是使用哈希查找.

.net c# hash dictionary

116
推荐指数
3
解决办法
2万
查看次数

在c#字典中只有一个查找的查找或插入

我是一名前C++/STL程序员,试图使用c#/ .NET技术编写快速行进算法...

我正在搜索等效的STL方法"map :: insert",如果不存在,则在给定键处插入值,否则返回现有键值对的迭代器.

我找到的唯一方法是使用两个查找:一个在TryGetValue中,另一个在Add方法中:

List<Point> list;
if (!_dictionary.TryGetValue (pcost, out list))
{
    list = new List<Point> ();
    dictionary.Add (pcost, list);
}
list.Add (new Point { X = n.x, Y = n.y });
Run Code Online (Sandbox Code Playgroud)

是否有一些东西可以解释为什么使用.NET容器不可能?还是我错过了一些观点?

谢谢.

c# lookup comparison performance stl

10
推荐指数
2
解决办法
3724
查看次数

从Dictionary中"Check Add or Fetch"组合

我厌倦了这个字典成语:

        Dictionary<Guid,Contact> Contacts;
        //...
        if (!Contacts.ContainsKey(id))
        {
            contact = new Contact();
            Contacts[id] = contact;
        }
        else
        {
            contact = Contacts[id];
        }
Run Code Online (Sandbox Code Playgroud)

如果有一种语法允许从默认构造函数隐式创建新值,如果它不存在(字典知道值的类型,毕竟),那将是很好的.有人看过这样做的助手(例如扩展方法)吗?

c# collections syntax extension-methods dictionary

4
推荐指数
1
解决办法
1550
查看次数