【问题标题】:How can you convert a List<X> to Dictionary<X,Y> filling the value with null?如何将 List<X> 转换为 Dictionary<X,Y> 用 null 填充值?
【发布时间】:2014-12-12 23:02:38
【问题描述】:

我正在尝试使用 List 作为键和 null 作为值来填充字典。我怎样才能做到这一点?我正在用 C# 编程

谢谢。

【问题讨论】:

  • @austinwernli 这似乎是在问别的问题

标签: c# linq list dictionary


【解决方案1】:

你也可以使用Linq Enumerable.ToDictionary,指定key和value为null:

var myList = new List<string> { "first", "second" };
Dictionary<string, string> dict = myList.ToDictionary(
    item => item,         // key 
    item => (string)null  // value
);

请注意,您需要将“null”转换为您的元素类型,否则 C# 无法推断出第二个 lambda 表达式的类型。

【讨论】:

  • 这是我尝试过的,但我收到以下错误:“无法将 lambda 表达式转换为类型 'System.Collections.Generic.IEqualityComparer' 因为它不是委托类型”
  • @Negashion 我注意到,在我发布之后——查看我的编辑。您只需要将 null 转换为确定的类型。 (C# 不能从空引用推断任何类型。)
  • 好的,我刚看到你的编辑。那个该死的演员给我带来了麻烦! =) 谢谢,很有魅力。
  • 字典,默认值为 0 var res = myList.Distinct().ToDictionary(x => x, x => Convert.ToInt32("0"));
【解决方案2】:

只使用一个循环就足够简单了:

foreach (var item in myList)
   myDictionary.Add(item, null);

当然,这假设您已经创建了Dictionary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2011-11-15
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多