如何检查" id"是null还是空,那么默认值是0还是空字符串?

时间:2017-02-20 07:36:01

标签: c# linq

我在C#中使用LINQ编写代码。代码工作正常,但是当我尝试测试时,没有数据没有值,我知道如果id为null或为空,它将跳过LINQ查询。如果跳过LINQ查询,如何将查询结果的值设置为零或空字符串?

var  Rs1 = _context.DwPropertyDetails.Where(x => x.LandId == id && x.TransactionPrice != null)
                    .Select(x => new
                    {
                        Studio = x.FlatType.ToLower() == studio.ToLower() ? x.TransactionPrice : 0,
                        OneBedroom = x.FlatType.ToLower() == onebedroom.ToLower() ? x.TransactionPrice : 0,
                        TwoBedroom = x.FlatType.ToLower() == twobedroom.ToLower() ? x.TransactionPrice : 0,
                        ThreeBedroom = x.FlatType.ToLower() == threebedroom.ToLower() ? x.TransactionPrice : 0,
                        Total = x.TransactionPrice
                    }).Select(a => new
                    {
                        a.Studio,
                        a.OneBedroom,
                        a.TwoBedroom,
                        a.ThreeBedroom,
                        a.Total,
                        Dummy = "x"
                    }).GroupBy(a => new { a.Dummy })
                    .Select(g => new
                    {
                        Rs1Clm2 = totalTransAmount,
                        Rs1Clm3 = g.Sum(p => p.Studio),
                        Rs1Clm4 = g.Sum(p => p.OneBedroom),
                        Rs1Clm5 = g.Sum(p => p.TwoBedroom),
                        Rs1Clm6 = g.Sum(p => p.ThreeBedroom),
                        Rs1Clm7 = g.Sum(p => p.Total),
                    });

我在视图中尝试它

<tbody>
            @if (Model == null || string.IsNullOrEmpty(Model.Rs1Vms.ToString()) || string.IsNullOrWhiteSpace(Model.Rs1Vms.ToString()))
            {
                <tr>
                    <td>Total Transaction Amount</td>
                    <td>0</td>
                    <td>0</td>
                    <td>0</td>
                    <td>0</td>
                    <td>0</td>
                </tr>
            }
            else
            {
                foreach (var a in Model.Rs1Vms)
                {
                    <tr>
                        <td>@Html.DisplayFor(model => a.Rs1Vm2)</td>
                        <td>@($"{a.Rs1Vm3:N0}")</td>
                        <td>@($"{a.Rs1Vm4:N0}")</td>
                        <td>@($"{a.Rs1Vm5:N0}")</td>
                        <td>@($"{a.Rs1Vm6:N0}")</td>
                        <td>@($"{a.Rs1Vm7:N0}")</td>
                    </tr>
                }
            }
        </tbody>

1 个答案:

答案 0 :(得分:0)

您可以使用 DefaultIfEmpty 执行此任务。

var Rs2 = Rs1.DefaultIfEmpty(new
                    {
                        Rs1Clm2 = 0,
                        Rs1Clm3 = 0,
                        Rs1Clm4 = 0,
                        Rs1Clm5 = 0,
                        Rs1Clm6 = 0,
                        Rs1Clm7 = 0,
                    });