如何在C#中忽略Dictionary <k,list <t =“” >>中的项List <t>

时间:2019-05-30 13:17:06

标签: c# linq lambda

我必须忽略其产品类型不包含在字典内给定字符串中的项目(列表)。

我试图在foreach循环中迭代字典并检查循环中的产品类型,并且工作正常,但是我想在不进行迭代的情况下使用它,无论如何都可以实现这一目标?

private ConcurrentDictionary<string, List<PAAMsg>> FilterAllowedProductsTrades(ConcurrentDictionary<string, List<PAAMsg>> allPAA)
{
    ConcurrentDictionary<string, List<PAAMsg>> newPAA = new ConcurrentDictionary<string, List<PAAMsg>>();
    string productType = "BFO,BFT,BOND FWD,CAP,FEE,FEX,FRA,FUT,FxFUT,MFO,SWP,OFT,SWT";

    foreach (var item in allPAA)
    {
        newPAA.TryAdd(
            item.Key, 
            item.Value.FindAll((x => productType.Split(',').Contains(x.ProductType)))
        .ToList());
    }
    return newPAA;
}

我想避免下面的迭代,应该放在一行中。

foreach (var item in allPAA)
{
    newPAA.TryAdd(
        item.Key, 
        item.Value.FindAll((x => productType.Split(',').Contains(x.ProductType))).ToList());
}

1 个答案:

答案 0 :(得分:3)

我认为不可能避免循环,LINQ只会将其隐藏在其语法后面。因此,这是一个优先事项。

一个可能的替代方案如下:

private ConcurrentDictionary<string, List<PAAMsg>> FilterAllowedProductsTrades(ConcurrentDictionary<string, List<PAAMsg>> allPAA)
{
    string productType = "BFO,BFT,BOND FWD,CAP,FEE,FEX,FRA,FUT,FxFUT,MFO,SWP,OFT,SWT";
    var productTypes = productType.Split(',');

    var enumeration = allPAA.ToDictionary(
            x => x.Key, 
            x => x.Value.Where(p => productTypes.Contains(p.ProductType)).ToList());

    return new ConcurrentDictionary<string, List<PAAMsg>>(enumeration);
}

我也建议将Split操作移出循环。

相关问题