我发现自己现在经常在我的代码中使用当前模式
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)
现在,我可以为字典类编写一个扩展方法来为我做这个,但我想我可能会遗漏已经存在的东西.那么,有没有办法以更简单的方式做到这一点,而无需在字典中编写扩展方法?
如果缺少键,则Index into Dictionary会引发异常.是否有IDictionary的实现,而是返回默认值(T)?
我知道"TryGetValue"方法,但这不可能与linq一起使用.
这会有效地做我需要的吗?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
Run Code Online (Sandbox Code Playgroud)
我认为它不会,因为我认为它将迭代键而不是使用哈希查找.
在这个帖子中
如何获取null而不是按键访问字典值的KeyNotFoundException?
在我自己的回答中,我使用显式接口实现来更改基本字典索引器行为,KeyNotFoundException如果字符中没有键,则不要抛出(因为null在这种情况下我很方便获得内联).
这里是:
public interface INullValueDictionary<T, U>
where U : class
{
U this[T key] { get; }
}
public class NullValueDictionary<T, U> : Dictionary<T, U>, INullValueDictionary<T, U>
where U : class
{
U INullValueDictionary<T, U>.this[T key]
{
get
{
if (ContainsKey(key))
return this[key];
else
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为在一个真实的应用程序中我有一个字典列表,我需要一种方法来从集合中访问字典作为接口.我使用简单的int索引器来访问列表的每个元素.
var list = new List<NullValueDictionary<string, string>>();
int index = 0;
//...
list[index]["somekey"] = "somevalue";
Run Code Online (Sandbox Code Playgroud)
最简单的事情是做这样的事情:
var idict = (INullValueDictionary<string, string>)list[index];
string value …Run Code Online (Sandbox Code Playgroud) 我对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)
再次,我完全有能力编写自己的帮助函数.在我这样做之前,我正在寻找现有的本机功能或简写.
c# ×4
dictionary ×2
.net ×1
collections ×1
covariance ×1
generics ×1
hash ×1
indexer ×1
interface ×1
trygetvalue ×1