【问题标题】:Flattening a Dictionary of Dictionaries With SelectMany()使用 SelectMany() 展平字典
【发布时间】:2012-08-19 22:36:46
【问题描述】:

我有这些词典:

public class CiscoVSAN
{
    private string _VSANName;
    private string _VSANNum;
    public string VSANName{ get{return _VSANName;} set{_VSANName=value;} }
    public string VSANNum{ get{return _VSANNum;} set{_VSANNum=value;} }

    public Dictionary<int, CiscoSwitch> MemberSwitches = new Dictionary<int, CiscoSwitch>();
}

public Dictionary<int, CiscoVSAN> VSANList = new Dictionary<int, CiscoVSAN>();

我正在尝试替换这个 foreach

foreach (KeyValuePair<int, CiscoVSAN> vsanpair in this.VSANList)
{
    var currSwitchAsEnumerable  = vsanpair.Value.MemberSwitches.Where(cs => cs.Value.switchName == RemoteSwitchName);
    if (currSwitchAsEnumerable != null)
    {
        //currVSAN.MemberSwitches.Add(DomainID, currSwitchAsEnumerable.FirstOrDefault().Value);
        currSwitch = currSwitchAsEnumerable.FirstOrDefault().Value;
        break;
    }
}

在外部字典上有一个 SelectMany。我想要 MemberSwitches 中与条件匹配的第一个匹配项。并非所有 VSAN 在其各自的字典中都有相同的成员交换机。我试过这个:

var selectmany = this.VSANList.SelectMany(cs => cs.Value).Where( => cs).Where(cs.Value.SwitchName == RemoteSwitchName).First(); 

还有这个:

var selectmany = this.VSANList.Values.SelectMany(cs => cs.Value).Where( => cs).Where(cs.Value.SwitchName == RemoteSwitchName).First();

但是每次编译器告诉我它不能从使用中推断出类型参数。我还尝试在 SelectMany 语句之后为其提供类型参数,但这也不起作用。我查看的大多数示例要么是扁平化的列表列表,要么是简单的字典。他们也没有在 SelectMany 上指定任何类型。

编辑添加我试过这个:

Dictionary<int, List<string>> mydict = new Dictionary<int, List<string>>();
var selectlist = mydict.Values.SelectMany(n => n).ToList();

并且没有得到关于推断类型的编译器错误。所以然后我尝试了这个,只是为了将字典展平并将其转换为列表:

var selectmany = this.VSANList.Values.SelectMany(vs => vs).ToList();

我再次收到编译器警告。我不确定要指定什么类型或如何指定它。

【问题讨论】:

  • .Where( =&gt; cs) 语法看起来无效。

标签: c# linq dictionary


【解决方案1】:

假设没有拼写错误,您有一个语法错误:.Where ( =&gt; cs ) 部分是非法的。你想在这里表达什么?

编辑:

实际上,仔细想想,你的整个表达都是非法的或输入错误的。

您传递给 SelectMany 的委托应返回 IEnumerable&lt;T&gt;,但您的表达式返回 CiscoVSAN

【讨论】:

  • 抱歉应该是 .Where(cs => cs) 我修复了这个问题,但仍然收到有关推断类型的消息。
  • @David:仍然输入错误。传递给 Where() 的委托应该返回一个布尔值。
  • 好的...这来自另一个帖子:
【解决方案2】:

我想通了:

var selectmany = this.VSANList.Values.SelectMany(vs => vs.MemberSwitches).Where(cs => cs.Value.switchName == RemoteSwitchName).First();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2021-06-02
    • 2016-01-06
    • 2020-06-16
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    相关资源
    最近更新 更多