linq多单表和多表的条件查询

2025-04-28 08:41:50
推荐回答(1个)
回答1:

动态查询说简单也简单,比如你上述仅仅两个字段的判断,说复杂也复杂,如果要做到任意字段名和值的选项。下面只给你写出【简单】的示例代码

    class Program
    {
        static void Main(string[] args)
        {
            List lst = new List
            {
                new U(1,"a",20),
                new U(2,"b",20),
                new U(3,"a",30),
                new U(4,"c",20)
            };

            //var v = Search(lst, "a", 30);//3
            //var v = Search(lst, "a", 20);//1
            var v = Search(lst, "", 20);//1,2,4

            foreach (U u in v)
                Console.WriteLine(u);

            Console.ReadLine();

        }

        static List Search(List lst, string n, int a)
        {
            var v = lst.Where(x => true);
            if (!string.IsNullOrWhiteSpace(n))
                v = v.Where(x => x.N == n);
            if (a > 0)
                v = v.Where(x => x.A == a);
            return v.ToList();
        }
    }

    public class U
    {
        public U(int i, string n, int a)
        { I = i; N = n; A = a; }
        public int I;
        public string N;
        public int A;

        public override string ToString()
        {
            return string.Format("I={0}\tN={1}\tA={2}\n", I, N, A);
        }
    }