Java 中使用Linq
maven安装。
<dependency> <groupId>com.bestvike</groupId> <artifactId>linq</artifactId> <version>3.1.0</version> </dependency>
带where查询
//方法链 var ddd = Linq.of(list).where(x -> x.getAge() > 15).toList(); //sql String sql = "select * from user where age>15";
简单的函数计算(max、min、count、sum)
//方法链 //var ddd = Linq.of(list).max(x -> x.getAge());//获取最大的年龄 //var ddd = Linq.of(list).min(x -> x.getAge());//获取最小的年龄 //var ddd = Linq.of(list).count();//获取总数 var ddd = Linq.of(list).sumInt(x -> x.getAge());//获取总数 //sql //String sql = "select max(age) from user"; //String sql = "select min(age) from user"; //String sql = "select count(1) from user"; String sql = "select sum(age) from user";
排序
//方法链 //var ddd = Linq.of(list).orderBy(x -> x.getAge());//正序 var ddd = Linq.of(list).orderByDescending(x -> x.getAge());//倒序 //sql //String sql = "select * from user order by age"; String sql = "select * from user order by age desc";
top1
//方法链 var ddd = Linq.of(list).firstOrDefault(); //sql String sql = "select top 1 from user";
跳过前面多少条数据,取剩下的数据
//方法链 var ddd = Linq.of(list).orderByDescending(x -> x.getAge()).skip(1); //sql String sql = "select * from (select ROW_NUMBER() over(order by age desc) as rowNum,*) t wher rowNum>1";
分页查询
//方法链 //跳过第一条,取两条,即取第二条到第四条 var ddd = Linq.of(list).orderByDescending(x -> x.getAge()).skip(1).take(3); //sql String sql = "select * from (select ROW_NUMBER() over(order by age desc) as rowNum,*) t wher rowNum>1 and rowNum<=4";
包含,相当于like
//方法链 var ddd = Linq.of(list).where(x->x.getName().contains("李")); //sql String sql = "select * from user where name like '%李%'";
分组group by
//方法链 var ddd = Linq.of(list).groupBy(x -> x.getAge()).toList(); for (var t : ddd) { System.out.println(t.getKey() + "--" + t.minInt(x -> x.getMoney()) + "--" + t.maxInt(x -> x.getMoney()) + "--" + t.sumInt(x -> x.getMoney())); } //sql String sql = "select age,min(money),max(money),sum(money) from user group by age";
sql中的in
//方法链 List<Integer> ages = new ArrayList<>(); ages.add(15); ages.add(16); var ddd = Linq.of(list).where(x -> ages.contains(x.getAge())); //sql String sql = "select * from user where age in (15,16)";