我有一个数据表,我正在尝试对列实施服务器端过滤。我允许每列查询多个字符串,并试图确定逐步遍历所有过滤器的最佳方法。下面是表对象的示例,为简单起见,仅包含两个参数。

//table models from db
public class Parts
{
    public string PartName { get; set; }
    public virtual Series Series { get; set; }
}

public class Series
{
    public string SeriesName { get; set; }
}

//This is what is passed in from the datatable filter query
public class PartsTable
{
    public string PartName { get; set; }

    public string SeriesName { get; set; }
}


public IEnumerable<Parts> PartsTableSearch(PartsTable table)
{
    //Queries come in as comma separated string
    var partNameList = table.PartName?.Split(',');
    var seriesNameList = table.SeriesName?.Split(',');

    //Gets and generates the list of Parts
    var fullList = GetParts();

    if (partNameList != null && partNameList.Length > 0)
    {
        foreach (var partName in partNameList)
        {
            fullList = fullList.Where(p => p.PartName.ToLower().Contains(name.ToLower()));
        }
    }
    if (seriesNameList != null && seriesNameList.Length > 0)
    {
        foreach (var seriesName in seriesNameList)
        {
            fullList = fullList.Where(p => p.Series.SeriesName.ToLower().Contains(seriesName.ToLower()));
        }
    }

    return fullList;
}


这将无法满足我的需求,因为对于每个参数(即PartName),我需要能够返回所有具有PartName的对象,这些PartName包含partNameList中的搜索字符串,然后从该结果中进一步过滤在seriesNameList中包含搜索字符串的SeriesNames,然后返回结果集。但是,对partNameList的查询可能为空,并且仅搜索seriesName,反之亦然。有什么建议么?我觉得这是一个显而易见的答案,我只是忽略了,尽管我搜索的其他任何内容仅适用于单个查询过滤器。提前致谢。

最佳答案

可以通过两种方式使用单个.Where来完成此操作:

使用.Contain()将返回完全匹配项:

public IEnumerable<Parts> PartsTableSearch(PartsTable table)
{
    //Queries come in as comma separated string
    var partNameList = table.PartName?.Split(',');
    var seriesNameList = table.SeriesName?.Split(',');

    //Gets and generates the list of Parts
    var fullList = GetParts()
        .Where(p => partNameList.Contains(p.PartName.ToLower())
            || seriesNameList.Contains(p.Series.SeriesName.ToLower()))
        .ToList();

    return fullList;
}


使用.Any()将返回部分匹配:

public IEnumerable<Parts> PartsTableSearch(PartsTable table)
{
    //Queries come in as comma separated string
    var partNameList = table.PartName?.Split(',');
    var seriesNameList = table.SeriesName?.Split(',');

    //Gets and generates the list of Parts
    var fullList = GetParts()
        .Where(p => partNameList.Any(n => n.Contains(p.PartName.ToLower())))
            || seriesNameList.Any(n => n.Contains(p.Series.SeriesName.ToLower())))
        .ToList();

    return fullList;
}

07-28 01:35