从List>中查找值

本文关键字:查找 string List Dictionary | 更新日期: 2023-09-27 18:12:55

我有一个付款计划列表,并从中计算出每月价格的List<Dictionary<string, long>>

string = CampaignCode

long = Price Per Month

我不知道如何在我的视图中显示当前PaymentPlan的价格。

@Model.PaymentPlans.PricePerMonth.FirstOrDefault(x => x.)

这是我脑子里一片空白的地方。

public class PaymentPlansIncPPM
{
    public List<PaymentPlan> PaymentPlans { get; set; }
    public List<Dictionary<string, long>> PricePerMonth { get; set; }
}

@foreach (var plan in Model.PaymentPlans)
{
    <div>
        @Html.RadioButton("CampaignId", plan.CampaignCode, new { @id = plan.CampaignCode })
        <label for="@plan.CampaignCode"></label>
        <span>
            <b>@plan.ContractLengthInMonths months</b><br />
            
<-- Here is where I want to show the price per month -->
             $/month
        </span>
    </div>
}

编辑:字典包含一个或多个,总是匹配计划的数量。(如果有帮助的话)

Key "campaignCode"  string
Value   100000  long
Key "pricePerMonth" string
Value   42  long

从List<Dictionary<string >>中查找值

您可以从键和列表之间的循环访问Dictionary。示例:

@foreach (var plan in Model.PaymentPlans)
{
    <div>
        @Html.RadioButton("CampaignId", plan.CampaignCode, new { @id = plan.CampaignCode })
        <label for="@plan.CampaignCode"></label>
        <span>
            <strong>@plan.ContractLengthInMonths months</strong><br />
            @{
                var prices = plan.PricePerMonth.FirstOrDefault(d => d.ContainsKey(plan.CampaignCode));
               if (prices != null)
               {
                   foreach(long price in prices[plan.CampaignCode])
                   {
                       <text>
                       <li>@price</li>
                       </text>
                   }    
               }
            }           
             $/month
        </span>
    </div>
}

给定你的模型上有一个字典列表,你可以找到一个字典,那里有一个Key等于你的CampaignCode,并显示这个Key的值。我将代码更改为显示CampaignCode的第一次出现,但在此结构中,您可以有几个。

如果List<Dictionary<string, long>>看起来像这样

PricePerMonth (list) :
dict1: [
        {Key: "campaignCode", Value:  100000},
        {Key: "pricePerMonth", Value: 42}
    ]
dict2: [
        {Key: "campaignCode", Value:  100001},
        {Key: "pricePerMonth", Value: 29}
    ]
dict3: [
        {Key: "campaignCode", Value:  100002},
        {Key: "pricePerMonth", Value: 51}
    ]

你可以通过

获取活动的"每月价格"(plan.CampaignCode)
var correctDict = Model.PriceMonth.First(dict => dict["campaignCode"] == plan.CampaignCode);
var pricePerMonth = correctDict["pricePerMonth"];