用if语句选择新的

时间:2018-11-28 09:36:48

标签: c# .net linq if-statement

我有这段代码可以从我的C#项目中的数据库中选择一些新信息,但我只希望它在名称不是一个特定名称的情况下执行此操作,所以这是代码

public List<Info> GetInfo(int id)
{
    var cacheKey = "allinfo-" + id;
    var info = SoftCache.GetData<List<info>>(cacheKey);
    if (info != null)
        return info;

    using (var db = DB.InfoModel)
    {
        info = (from j in db.info_list()

                select new Info
                {
                    InfoName = j.info_name,
                    InfoId = j.info_id,
                    InfoValue = j.info_value,
                }).ToList();
    }

    SoftCache.Add(cacheKey, info, new TimeSpan(0, 0, 5), new TimeSpan(0, 1, 0));
    return info;
}

我想要的是类似的东西

if(j.info_name != "BadName"){
    select new Info
    {
        InfoName = j.info_name,
        InfoId = j.info_id,
        InfoValue = j.info_value,
    }).ToList();
}

3 个答案:

答案 0 :(得分:2)

您需要在此处添加where语句:

info = (from j in db.info_list()
where j.info_name != "BadName"
select new Info
{
    InfoName = j.info_name,
    InfoId = j.info_id,
    InfoValue = j.info_value,
}).ToList();

答案 1 :(得分:2)

您可以使用where来过滤信息,如下所示:-

info = (from j in db.info_list()
where j.info_name != "BadName"
select new Info
{
    InfoName = j.info_name,
    InfoId = j.info_id,
    InfoValue = j.info_value,
}).ToList();

答案 2 :(得分:2)

或通过使用Where扩展方法

var goodNames = 
    db.info_list().Where(info => info.info_name != "Badname")
                  .Select(info => new Info
                  {
                      InfoName = info.info_name,
                      InfoId = info.info_id,
                      InfoValue = info.info_value,
                  })
                  .ToList();