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();

        }

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM