相关疑难解决方法(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万
查看次数

是否有内置的通用接口,索引器返回了协变类型参数?

在这个帖子中

如何获取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# generics indexer interface covariance

7
推荐指数
1
解决办法
279
查看次数

更少错误TryGetValue然后null检查语法

我对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# null-coalescing-operator trygetvalue

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