我有一个项目列表,称为翻译。我根据搜索框中的搜索词过滤翻译,目前它看起来像这样:
private static IList<Translation> FilterTranslationListOLD(string filter, IEnumerable<Translation> translationList)
{
filter = filter.ToLower();
if (!string.IsNullOrEmpty(filter))
{
return translationList
.Where(t => (t.Tag.Filename.ToLower().Contains(filter)
|| t.Tag.FilePath.ToLower().Contains(filter)
|| t.Tag.TagContent.ToLower().Contains(filter)
|| (t.Tag.SanitizedTagContent != null && t.Tag.SanitizedTagContent.ToLower().Contains(filter))
|| (t.TagTranslation != null && t.TagTranslation.ToLower().Contains(filter))
|| (t.SanitizedTranslation != null && t.SanitizedTranslation.ToLower().Contains(filter))))
.OrderBy(t => t.Tag.FilePath)
.ThenBy(t => t.Tag.Filename).ThenBy(t => t.Tag.Id).ToList();
}
return translationList.OrderByDescending(t => t.DateTranslated).ToList();
}
我现在介绍了使用多个关键字进行搜索的功能,如下所示:
private static IList<Translation> FilterTranslationList(string filter, IEnumerable<Translation> translationList)
{
filter = filter.ToLower();
var splitFilterTerms = filter.Split(',');
if (splitFilterTerms.Any(split=>!string.IsNullOrEmpty(split)))
{
var translationListResults = new List<Translation>();
foreach (var splitFilterTerm in splitFilterTerms)
{
translationListResults.AddRange(translationList
.Where(t => (t.Tag.Filename.ToLower().Contains(splitFilterTerm)
|| t.Tag.FilePath.ToLower().Contains(splitFilterTerm)
|| t.Tag.TagContent.ToLower().Contains(splitFilterTerm)
|| (t.Tag.SanitizedTagContent != null && t.Tag.SanitizedTagContent.ToLower().Contains(splitFilterTerm))
|| (t.TagTranslation != null && t.TagTranslation.ToLower().Contains(splitFilterTerm))
|| (t.SanitizedTranslation != null && t.SanitizedTranslation.ToLower().Contains(splitFilterTerm))))
.OrderBy(t => t.Tag.FilePath)
.ThenBy(t => t.Tag.Filename).ThenBy(t => t.Tag.Id).ToList());
}
return translationListResults;
}
return translationList.OrderByDescending(t => t.DateTranslated).ToList();
}
我想知道的是,有没有更好的写法?虽然它有效,但很高兴知道如何在所有 linq 中执行此操作或稍微减少/重构它(让它更整洁一些)。提前致谢!