从MSDN上的Dictionary.TryGetValue方法入口:
此方法结合了ContainsKey方法和Item属性的功能.
如果未找到密钥,则value参数将获取值类型TValue的相应默认值; 例如,0(零)表示整数类型,false表示布尔类型,null表示引用类型.
如果您的代码经常尝试访问不在字典中的键,请使用TryGetValue方法.使用此方法比捕获Item属性抛出的KeyNotFoundException更有效.
该方法接近O(1)操作.
从描述中,不清楚它是否比调用ContainsKey然后进行查找更有效或更方便.TryGetValue通过执行单个查找,只调用ContainsKey然后调用Item或实际上是否更有效?
换句话说,什么是更有效(即哪一个执行更少的查找):
Dictionary<int,int> dict;
//...//
int ival;
if(dict.ContainsKey(ikey))
{
ival = dict[ikey];
}
else
{
ival = default(int);
}
Run Code Online (Sandbox Code Playgroud)
要么
Dictionary<int,int> dict;
//...//
int ival;
dict.TryGetValue(ikey, out ival);
Run Code Online (Sandbox Code Playgroud)
注意:我不是在寻找基准!
如果缺少键,则Index into Dictionary会引发异常.是否有IDictionary的实现,而是返回默认值(T)?
我知道"TryGetValue"方法,但这不可能与linq一起使用.
这会有效地做我需要的吗?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
Run Code Online (Sandbox Code Playgroud)
我认为它不会,因为我认为它将迭代键而不是使用哈希查找.
在某些情况下,当字典中没有这样的键时,对于我来说,有一个简短的,可读的方式来获取null而不是KeyNotFoundException按键访问字典值,这似乎是有用的.
我想到的第一件事是扩展方法:
public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
where U : class //it's acceptable for me to have this constraint
{
if (dict.ContainsKey(key))
return dict[key];
else
//it could be default(U) to use without U class constraint
//however, I didn't need this.
return null;
}
Run Code Online (Sandbox Code Playgroud)
但是当你写下这样的东西时,它实际上并不是很短暂的说法:
string.Format("{0}:{1};{2}:{3}",
dict.GetValueByKeyOrNull("key1"),
dict.GetValueByKeyOrNull("key2"),
dict.GetValueByKeyOrNull("key3"),
dict.GetValueByKeyOrNull("key4"));
Run Code Online (Sandbox Code Playgroud)
我会说,有一些接近基本语法的东西要好得多:dict["key4"].
然后我想出了一个带有private字典字段的类的想法,它暴露了我需要的功能:
public class MyDictionary<T, U> //here I may add any of interfaces, implemented
//by dictionary itself to …Run Code Online (Sandbox Code Playgroud) 我经常发现自己创建了Dictionary一个非平凡的值类(例如List),然后在填充数据时总是编写相同的代码模式.
例如:
var dict = new Dictionary<string, List<string>>();
string key = "foo";
string aValueForKey = "bar";
Run Code Online (Sandbox Code Playgroud)
也就是说,我想插入"bar"与key对应的列表"foo",其中key "foo"可能不会映射到任何内容.
这是我使用不断重复的模式的地方:
List<string> keyValues;
if (!dict.TryGetValue(key, out keyValues))
dict.Add(key, keyValues = new List<string>());
keyValues.Add(aValueForKey);
Run Code Online (Sandbox Code Playgroud)
有更优雅的方式吗?
相关问题没有这个问题的答案:
我有一个消息列表.每条消息都有一个类型.
public enum MessageType
{
Foo = 0,
Bar = 1,
Boo = 2,
Doo = 3
}
Run Code Online (Sandbox Code Playgroud)
枚举名称是任意的,无法更改.
我需要返回列表排序为:Boo,Bar,Foo,Doo
我目前的解决方案是创建一个tempList,按我想要的顺序添加值,返回新列表.
List<Message> tempList = new List<Message>();
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Boo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Bar));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Foo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Doo));
messageList = tempList;
Run Code Online (Sandbox Code Playgroud)
我怎么能用IComparer做到这一点?
是否有Python的.NET模拟defaultdict?我发现编写短代码很有用,例如.计数频率:
>>> words = "to be or not to be".split()
>>> print words
['to', 'be', 'or', 'not', 'to', 'be']
>>> from collections import defaultdict
>>> frequencies = defaultdict(int)
>>> for word in words:
... frequencies[word] += 1
...
>>> print frequencies
defaultdict(<type 'int'>, {'not': 1, 'to': 2, 'or': 1, 'be': 2})
Run Code Online (Sandbox Code Playgroud)
理想情况下,在C#中,我可以写:
var frequencies = new DefaultDictionary<string,int>(() => 0);
foreach(string word in words)
{
frequencies[word] += 1
}
Run Code Online (Sandbox Code Playgroud) 有没有办法写这个更紧凑?
return _searchRedirectionMap.ContainsKey(query) ? _searchRedirectionMap[query] : "";
Run Code Online (Sandbox Code Playgroud)
Givent _searchRedirectionMap被定义为IDictionary<string,string>
我有以下 PageViewModel 类:
public class PageViewModel : ViewModel<Page>
{
public PageViewModel ()
{
Kywords = new List<Keyword>();
AnswserKeywordDictionary = new Dictionary<string, Answer>();
}
public Company Company { get; set; }
public List<Keyword> Kywords { get; set; }
public Dictionary<string, Answer> AnswserKeywordDictionary { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我正在使用 AnswserKeywordDictionary 属性,如下所示:
@Html.DisplayAffirmativeAnswer(Model.AnswserKeywordDictionary["myKey"])
Run Code Online (Sandbox Code Playgroud)
我的问题是:如果“myKey”不在字典中,我如何返回默认值。
提前致谢
我对C#还有点新鲜......我发现自己一遍又一遍地重复使用特定的程序.在我为个人懒惰写一个辅助方法之前,是否有更短或更少的错误方式来编写这种陈述?
Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
CreatedBy = createdBy ?? "Unknown",
//set 15 other values
...
}
Run Code Online (Sandbox Code Playgroud)
本质上,通过尝试获取值来设置对象的属性,然后如果它为null则使用默认值.我有很多属性,如果我可以的话会更好
MyEntity me = new MyEntity{
CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
...
}
Run Code Online (Sandbox Code Playgroud)
再次,我完全有能力编写自己的帮助函数.在我这样做之前,我正在寻找现有的本机功能或简写.