【问题标题】:Use .ToDictionary to return another Dictionary type使用 .ToDictionary 返回另一个 Dictionary 类型
【发布时间】:2012-07-27 07:24:25
【问题描述】:

我有一本字典,它的类型是 Dictionary<int, fooClass> fooDic,另一个字典是 Dictionary<int, string> barlist,我正在使用这个 linq 返回结果

var foobarList = fooDic.Where(kvp => 
       !barlist.ContainsKey(((fooClass)kvp.Value)._fooID))
       .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

这将返回 fooDic 类型的结果。但我需要将强制转换输出键入为barlist(Dictionary<int, string>) 类型。怎么样?

【问题讨论】:

  • 嗯,fooClass 不是 string(我假设)那么您想要执行哪种转换/转换?
  • 是的 J 你是对的 fooClass 是一些类..我需要输出为 Dictionary 类型...
  • 那么您将如何将 fooClass 转换为字符串?
  • 是的,我问你如何将fooClass 转换为string。你想在string 部分做什么? =)
  • 啊,对不起..我问错了......你是对的..你给了我一些想法......

标签: c# dictionary casting linq-to-objects


【解决方案1】:

如果这是一个相当简单的转换,关键是你的最后一部分

var foobarList = fooDic.Where(kvp => 
    !barlist.ContainsKey(((fooClass)kvp.Value)._fooID))
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

声明。在您当前使用 kvp => kvp.Value 的地方,您可以将其替换为 kvp => kvp.Value._foobarValue

根据 OP 的 cmets 编辑“完整”解决方案。

【讨论】:

  • 是的,你是对的......谢谢你的想法+1..我应该这样做 ToDictionary(kvp => kvp.Key, kvp => kvp.Value._foobarValue);应该是这样的……
【解决方案2】:

假设你的类 Foo 看起来像这样:

public class Foo
{
    public string SomeValue { get; set; }
    public int SomeOtherStuff { get; set; }
}

创建一个新字典:

var fooDict = new Dictionary<int, Foo>() {
    {0, new Foo() {SomeOtherStuff=10, SomeValue="some value"} },
    {1, new Foo() {SomeOtherStuff=15, SomeValue="some other value"} }
};

转换它:

Dictionary<int, string> stringDict = 
    fooDict.ToDictionary(x=> x.Key, x=> x.Value.SomeValue);  //<- note x.Value.SomeValue

stringDict 现在将包含:

{0, "some value"}, {1, "some other value"}

【讨论】:

  • 如果 J. Steen 的回答能够帮助您解决问题,您应该支持并接受他的回答。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2022-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多