ef 查询总结
1、Linq 查询两张表;a表和b表,要得到的数据是a表数据b表没有
例如:a表有5条数据1,2,3,4,5;b表有2条数据1,3;那么就用dataGridView1输出2,4,5;link语句要怎么写
from x in a where !b.Any(y=>y.id==x.id) select x;
------------------------------------- 转化成的sql类似如下
SELECT [t0].[ID] AS [ID] FROM [a] AS [t0] WHERE NOT (EXISTS( SELECT NULL AS [EMPTY] FROM [b] AS [t1] WHERE [t1].[ID] = [t0].[ID] ))
这样b表中没有的就输出了。
2、Linq获取两个List或数组的差集交集
List<int> list1 = new List<int>(); list1.Add(1); list1.Add(2); list1.Add(3); List<int> list2 = new List<int>(); list2.Add(3); list2.Add(4); list2.Add(5); //得到的结果是4,5 即减去了相同的元素。 List<int> list3 = list2.Except(list1).ToList(); foreach (int i in list3) { MessageBox.Show(i.ToString()); }
合并两个数组,并去掉重复元素,然后排序(C#)
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);
合并两个数组,并去除合并后的重复数据, 并排序
int[] A={1,2,2,3,4,5,6,6,6}; int[] B={2,2,2,3,7,8,9,5}; List<int> list = new List<int>(A); list.AddRange(B); list.Sort(); //去除重复项 foreach (int i in list.Distinct<int>()) { Console.WriteLine(i); }
C# 取两个数组的相同元素
以往我们都是肯定绞尽脑汁,肯定什么循环,元素大小,什么因素都考虑进去。但是现在采用Linq可以很好的解决这个问题。找出两个或多个数组的相同项。
代码相当简单:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespaceTest4_03 { classProgram { staticvoidMain(string[] args) { string[] names = {"Adams","Arthur","Buchanan","Tsbuchis","ShCian","FuchsiaLinda","DecheChen","Lotheer","FindLanciCade","SorchLand","JiangZheng","MisiiLoda","Gtod","Dfac","Lama","BakCades","Losangle","ZheWQ","GehengDahaLothi","ToryLandey","DakaLothy","BthLanda","MenNorth","Fith","FoxMain","DontM","Saobba","Del","Sala","Ghero","BhthLaPhda"}; IEnumerable<string> skip = names.Skip(10); IEnumerable<string> take = names.Take(11); //取出两个序列中交集部分,按理论应该输出JiangZheng IEnumerable<string> intersect = skip.Intersect(take); foreach(varsinintersect) { Console.WriteLine(s); } Console.ReadKey(); } } }