我该如何使用不执行任何操作的LINQ where子句?

时间:2018-09-26 10:37:19

标签: c# linq where

我拥有用于​​选择应用程序的Where子句的这段代码。

对于CVM.IncludeHidden,我不需要限制行并希望获得所有内容。但是我不确定该怎么做。如果是这种情况,我应该为where子句添加什么?

var select = " SELECT" +
                         " P.PhraseId, P.PhraseNum, P.English, P.Romaji, P.Kana, P.Kanji, P.Modified, P.WordType, P.Favorite," +
                         " P.Hidden, P.Viewed, P.Points, P.Score," +
                         " FROM Phrase" +
                         " WHERE P.Selected = 1 ";

List<Phrase> ps = db2.Query<Phrase>(select).ToList();
List<Phrase> psNoa = ps.Where(x => x.Points < noa).ToList();

Func<Phrase, bool> whereClause;

switch (Settings.cvm)
{
    case CVM.IncludeHidden:
        // I don't want to do any limiting
        // here I just want all records
        whereClause = ??
        break;
    case CVM.ExcludeHidden:
        whereClause = x => x.Hidden == false;
        break;
    case CVM.Hidden:
        whereClause = x => x.Hidden == true;
        break;
    case CVM.Favorites:
        whereClause = x => x.Favorite == true;
        break;
    default:
        return null;
}

return new SelectedPhrases()
{
    ps = ps.Where(whereClause).ToList(),
    psNoa = psNoa.Where(whereClause).ToList()
};

public class SelectedPhrases
{
    public List<Phrase> ps { get; set; }
    public List<Phrase> psNoa { get; set; }
}

1 个答案:

答案 0 :(得分:6)

Where扩展方法仅检查函数的结果是否为true。如果是这样,则通过。因此,只需返回true就足够了:

whereClause = x => true;

似乎您无缘无故创建了一个新列表。如果执行很多,它会影响您的表现。您还可以将whereClause设置为null,并在返回对象之前检查它:

if (whereClause != null)
{
    return new SelectedPhrases()
        {
            ps = ps.Where(whereClause).ToList(),
            psNoa = psNoa.Where(whereClause).ToList()
        };
}
else
{
    return new SelectedPhrases()
        {
            ps = ps,
            psNoa = psNoa
        };
}