在集合初始值设定项中使用条件

时间:2014-04-11 04:01:45

标签: c# dictionary

我想将一些值放入词典中:

//pretend these values are retrieved from a database or something
string firstName = "John";
string lastName = "Smith";

List<string> listHobbies = new List<string> () {"hockey","soccer"};

var dict = new Dictionary<string, dynamic>() 
{
    {"firstName", firstName},
    {"lastName", lastName},
    {"hobbies", listHobbies}
};

但是,在某些情况下,List<string>变量可能是一个空列表。如果是这种情况,我不想将{"hobbies", listHobbies}密钥添加到结果字典中。

有没有办法在字典的集合初始值设定项中实现此检查?或者我是否坚持使用if语句来检查列表的大小并在声明后立即删除密钥?

修改: 基本上,我想知道C#是否允许这样的事情:

var dict = new Dictionary<string, dynamic>() 
{
    {"firstName", firstName},
    {"lastName", lastName},
    {"hobbies", listHobbies} unless (listHobbies.Count == 0) //don't add the "hobbies" key if the list is empty.
};

我现在可以通过这样做来实现这一目标:

var dict = new Dictionary<string, dynamic>() 
{
    {"firstName", firstName},
    {"lastName", lastName},
    {"hobbies", listHobbies}
};
}.Concat(listHobbies != 0 ? new Dictionary<string, dynamic>() { { "hobbies", listHobbies } } : new Dictionary<string, dynamic>()).ToDictionary(k => k.Key, v => v.Value);

但这非常难看。

编辑2: 我找到了一个有些可接受的解决方案,如果其他人可以提供更好看的替代方案,请随时提出建议:

var dict = new Dictionary<string, dynamic>() 
{
    {"firstName", firstName},
    {"lastName", lastName},
    {"hobbies", !listHobbies.Any() ? listHobbies : null}
}
 .Where(entry => entry.Value != null)
 .ToDictionary(k => k.Key, v = v.Value);

1 个答案:

答案 0 :(得分:0)

这有什么问题?

var dict = new Dictionary<string, dynamic>() 
{
    {"firstName", firstName},
    {"lastName", lastName}
};
if (listHobbies.Any())
    dict.Add("hobbies", listHobbies);