Combine LINQ queries

后端 未结 3 868
情深已故
情深已故 2020-12-22 09:30

I\'m in the process of making a small query thing for a set of results of files.

public class f_results
    {
        public String name { get; set; }
               


        
3条回答
  •  忘掉有多难
    2020-12-22 10:20

    You could generate your filters beforehand, then apply them all at once - you would only have to iterate your initial enumeration once, something like this (shortened):

    IEnumerable foundfiles = new List();
    var filters = new List>();
    
    if (fsize.Text.Trim() != "")
    {
        long sz = long.Parse(fsize.Text);
        filters.Add(x => x.size >= sz);
    }
    
    if (adate.Text.Trim() != "")
    {
        DateTime test = DateTime.Parse(adate.Text);
        filters.Add(x => x.adate >= test);
    }
    
    foreach (var filter in filters)
    {
        var filterToApply = filter;
        foundfiles = foundfiles.Where(filterToApply);
    }
    finalResults = new BindingList(foundfiles);
    

    More importantly don't call ToList() until you have processed all filters, otherwise you keep iterating through your full result list over and over.

提交回复
热议问题