Build dynamic LINQ?

前端 未结 4 1415
我寻月下人不归
我寻月下人不归 2020-12-21 00:45

I\'m using LINQ to query data. Consider a case where the user only wants to report on say 1 of the 3 fields? (see below)

Can anyone tell me how to build the query d

4条回答
  •  一个人的身影
    2020-12-21 01:42

    like this:

    namespace overflow4
    {
        class Program
        {
            static void Main(string[] args)
            {
                var orig = new List() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    
                var newlist = FilterNumbers(orig, true, false, false);
    
                foreach (int x in newlist)
                    Console.WriteLine(x);
                Console.ReadLine();
            }
    
            private static IEnumerable FilterNumbers(
                List origlist, 
                bool wantMultiplesOf2, 
                bool wantMultiplesOf3, 
                bool wantMultiplesOf5)
            {
                IEnumerable sofar = origlist;
    
                if (wantMultiplesOf2)
                    sofar = sofar.Where(n => n % 2 == 0);
    
                if (wantMultiplesOf3)
                    sofar = sofar.Where(n => n % 3 == 0);
    
                if (wantMultiplesOf5)
                    sofar = sofar.Where(n => n % 5 == 0);
    
                return sofar;
            }
        }
    }
    

提交回复
热议问题