假如一个表有3列,line1,ine2,line3,
现在遇到一个情况是要根据前端用户的条件去选择shai'xuan哪一列,这个linq怎么写呢?
现在的做法是用switch 去判断:
switch(num){
case "1":
results = lines.Where(x=>x.line1.equals(...)).ToList();
break;
case "2":
results = lines.Where(x=>x.line2.equals(...)).ToList();
break;
...
}
请问有没有更好的方法呢?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Q1080766
{
class A
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
}
class Program
{
static void Main(string[] args)
{
int num = 1;
var p = Expression.Parameter(typeof(A), "p");
var getp = Expression.MakeMemberAccess(p, typeof(A).GetProperty("Line" + num.ToString()));
var body = Expression.Equal(getp, Expression.Constant("查询的值"));
var lambda = Expression.Lambda<Func<A, bool>>(body, p);
List<A> list = new List<A>();
list.Add(new A { Line1 = "查询的值", Line2 = "", Line3 = "" });
var query = list.AsQueryable().Where(lambda);
foreach (var item in query)
Console.WriteLine(item.Line1);
}
}
}
results = lines.Where(x=>
(num==1 && x.line1.equals(...))
|| (num==2 && x.line2.equals(...))
|| (num==3 && x.line3.equals(...))
).ToList();