IDictionary<String, List<OpenXmlCompositeElement>> - 获取列表<OpenXmlCompositeElement>?

IDictionary<String, List<OpenXmlCompositeElement>> - get the List<OpenXmlCompositeElement>?

我正在使用 Open XML 并且我有一个 IDictionary<String, List<OpenXmlCompositeElement>> 结构。我想使用结构的列表部分,但 this.map.Values 试图将其包装在 ICollection 中。如何从我的结构中获取列表部分?

    public List<OpenXmlCompositeElement> MapData()
    {
        //this does not work
        return this.map.Values;
    }

因为它是一本字典,所以它希望您从哪个键中分辨出您想要的值。

这就是您需要的代码,其中 yourKey 是您要检索的密钥:

public List<OpenXmlCompositeElement> MapData()
{
    return this.map["yourKey"];
}

如果您对密钥不感兴趣,并且字典只是一个字典,因为序列化器是这样说的,您可以获得第一个项目,例如:

public List<OpenXmlCompositeElement> MapData()
{
    return this.map.Values.First();
}

您可以遍历字典并使用您想要的值,或者直接使用键(在本例中是一个字符串)访问列表

IDictionary<String, List<OpenXmlCompositeElement>> myDictionary;

List<OpenXmlCompositeElement> myList = myDictionary["myKey"];

其中 myKey 在字典中可用。

或者你可以循环

foreach (var item in myDictionary)
{
    var key = item.Key;
    var value = item.Value

    // You could then use `key` if you are unsure of what
    // items are in the dictionary
}

假设这是你的字典...

IDictionary<string, List<OpenXmlCompositeElement>> items = ...;

按键获取特定列表...

List<OpenXmlCompositeElement> list = items["key"];

获取字典中的第一个列表...

List<OpenXmlCompositeElement> list = items.Values.First();

将字典中的所有列表连接成一个列表...

List<OpenXmlCompositeElement> list = items.SelectMany(o => o).ToList();
   foreach(KeyValuePair<string, List<OpenXmlCompositeElement>> kvp in IDictionary)
    {
    string key = kvp.key
    List<OpenXmlCompositeElement> list = kvp.Value;
        foreach(OpenXmlCompositeElement o in list)
        {
         Do anything you need to your List here
        }
    }

我也在使用字典,所以这是我目前正在使用的真实示例:

    foreach(KeyValuePair<string, List<DataRecords>> kvp in vSummaryResults)
        {
            string sKey = kvp.Key;
            List<DataRecords> list = kvp.Value;
            string[] vArr = sKey.Split(',');

            int iTotalTradedQuant = 0;
            double dAvgPrice = 0;
            double dSumQuantPrice = 0;
            double dQuantPrice = 0;
            double dNumClose = 0;

            foreach (DataRecords rec in list)
            {
                if(vSummaryResults.ContainsKey(sKey))
                {
                    iTotalTradedQuant += rec.iQuantity;
                    dQuantPrice = rec.iQuantity * rec.dInputTradePrice;
                    dSumQuantPrice += dQuantPrice;
                    dAvgPrice = dSumQuantPrice / iTotalTradedQuant;
                    dNumClose = rec.dNumericClosingPrice;

                }

                else
                {
                    vSummaryResults.Add(sKey, list);
                    //dNumClose = rec.dNumericClosingPrice;
                }