Linq 交集、并集等集合理论学习
作者:互联网
基于C#的Linq技术,如下代码整理:
private static void Linqtest() { /////1 List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 12, 10 }; List<int> numbers2 = new List<int>() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 }; var newQuerty = numbers1.Concat( from n in numbers2 where !numbers1.Contains(n) select n ).OrderBy(n => n); string count = ""; foreach (int i in newQuerty) { count += i + ","; } Console.WriteLine(count); ///2 List<int> list11 = new List<int>() { 1, 2, 3, 4, 4, 5, 6, 6 }; var newlist = list11.Distinct(); count = ""; foreach (int i in newlist) { count += i + ","; } Console.WriteLine(count); ///3 List<int> list12 = new List<int>() { 1, 2, 3, 4, 4, 5, 6, 6 }; List<int> list1 = new List<int>() { 5, 6, 6, 7, 8, 9 }; var newlist1 = list12.Union(list1); count = ""; foreach (int i in newlist1) { count += i + ","; } Console.WriteLine(count); //4 List<int> list13 = new List<int>() { 1, 2, 3, 4, 4, 5, 6, 6 }; List<int> list133 = new List<int>() { 5, 6, 6, 7, 8, 9 }; var newlist13 = list13.Intersect(list133); count = ""; foreach (int i in newlist13) { count += i + ","; } Console.WriteLine(count); //5 List<int> list14 = new List<int>() { 1, 2, 3, 4, 4, 5, 6, 6 }; List<int> list144 = new List<int>() { 5, 6, 6, 7, 8, 9 }; var newlist14 = list14.Except(list144); count = ""; foreach (int i in newlist14) { count += i + ","; } Console.WriteLine(count); }
命令行执行:
LINQ查询操作符的Distinct、Union、Concat、Intersect、Except、Skip、Take、SkipWhile、TakeWhile、Single、SingleOrDefault、Reverse、SelectMany,Aggregate()的使用,合并两个数组,并去掉重复元素,然后排序。
List<int> list= new List<int>() {1,2,3,4,4,5,6,6 }; var newlist=list.Skip (3); List<int> list= new List<int>() {1,2,2,3,4,4,5,6,6 }; var newlist=list.Take (3); Skip()和Take()方法都是IEnumerable 接口的扩展方法,包括C#中的所有Collections类,如ArrayList,Queue,Stack等等,还有数组和字符串都可以调用这两个方法。 var testList = new List(); //比如 testList里面是 1,2,3,4,5,6,7,8,9,10 var result = testList.Skip(5); //返回值就是 6,7,8,9,10;
var result = testList.Take(5); //返回值就是 1,2,3,4,5
//搭配使用,一般用来分页
var result = list.Skip(2).Take(2); //返回值 3,4
so:如果你刻意练习某件事情请超过10000小时,那么你就会达到世界级别。
标签:count,Console,并集,交集,List,Linq,Take,var,new 来源: https://www.cnblogs.com/shiningleo007/p/15718140.html