如何使用循环获取精确值列表结果

问题描述 投票:-2回答:1

这是我的数据库,其中列出了菜单的5个结果,

enter image description here

我想要的是,如果日期不等于当前日期(DateTime.Now),则结果将为零,如下所示:

enter image description here

这是我要执行的操作的代码,

for (int i = 1; i <= DateTime.Now.ToShortDateString().Length; i++)

            if (list.Any(x => x.Date.ToShortDateString() == i.ToString() ))
        {
            list.ToList().Add(new MenuModel
            {
                Total = list.First(x => x.Date.ToShortDateString() == i.ToString()).Total,
                Location = list.First(x => x.Date.ToShortDateString() == i.ToString()).Location,

            });
        }
        else
        {
            list.Add(new MenuModel
            {
                Total = list.First(x => x.Date.ToShortDateString() != i.ToString()).Total=0,
                Location = list.First(x => x.Date.ToShortDateString() != i.ToString()).Location,

            });

        }

但是我得到的结果是这样,

enter image description here

位置,未显示实际值,它将是A,B,C,D和E。如何获取位置的确切值?

c# loops
1个回答
2
投票

您真正需要的是一点linq魔法。下面的linq根据当前日期获取Total为实际值,如果不是当前日期,则将其设置为0。

DateTime date = DateTime.Today;
var menus = list.Select(l => new MenuModel
            {
                Total = l.Date.Date == date ? l.Total : 0,
                Location = l.Location,
            });
© www.soinside.com 2019 - 2024. All rights reserved.