【LINQ】
1,LINQ中实现从集合中查找在指定子集合中存在的记录
如有集合:List<user> 它有属性userid,username,它的值是
userid=1
username=“zzl”
userid=2
username=”lr”
userid=3
username=”zhz”
现在有要求,找到userid为1和3的user集合,怎么找?
已知得到用户集合名为userList
看我是这样实现的,如果大家有其它实现的方法,欢迎留言!
class User { public int UserID { get; set; } public string UserName { get; set; } } class Program { static void Main(string[] args) { List<User> userList = new List<User> { new User{UserID=1,UserName="zzl"}, new User{UserID=2,UserName="lr"}, new User{UserID=3,UserName="zhz"}, }; int[] userids = { 1, 3 }; userList.Where(i => userids.Contains(i.UserID)); } }
2,Linq的模糊查询
(1)利用linq提供的方法
n.Name.StartsWith(Name)--相当于A% n.Name.EndsWith(Name) --相当于%A n.Name.IndexOf(Name)!=-1 --相当于%A% var listWhere = list.Where(n=>n.Name.StartsWith(Name)||n.Name.EndsWith(Name)||n.Name.IndexOf(Name)!=-1); (2)利用集合提供的方法 var listWhere = list.Where(n=>n.Name.Contains(Name));
(3)需要引入 System.Data.Linq.SqlClient 命名空间
var query = from c in ctx.Customers where SqlMethods.Like(c.City, "%ab%") select c;
3,将表达式转化为SQL语句
using (testEntities MyEntity = new testEntities()) { #region linq to entities 内容练习3 var result = from s in MyEntity.stuinfo where s.username == "pkm" select new { username=s.username, age=s.age }; var psql = result.GetType().GetMethod("ToTraceString").Invoke(result, null);//得到原始sql语句 Console.WriteLine(psql); #endregion }