Linq Day1 - 查詢與排序

  • 1429
  • 0
  • 2017-09-01

此篇簡單介紹 Linq。

不錯的參考網站建議先看過一次 : 

http://ithelp.ithome.com.tw/users/20009278/ironman/450

https://dotblogs.com.tw/hatelove/series/1?qq=%E5%BF%AB%E5%BF%AB%E6%A8%82%E6%A8%82%E5%AD%B8LINQ%E7%B3%BB%E5%88%97


 

LinQ 是 .NET 提供一套對於物件集合標準查詢語法的框架。
_OrDefault  -大部分Linq查詢方法分成兩種 :  
查詢方法 : 抓取不到資料則會拋出例外
查詢方法OrDefault : 抓取不到資料則會回傳 null

資料模型 : 

using System;

namespace LinqDay1
{
    public class Model1
    {
        //訂單基本資料類別
        public class Order
        {
            public int CustomerId { get; set; }
            public DateTime OrderDate { get; set; }
            public double Total { get; set; }

            // 將屬性的值都印出來
            public override string ToString()
            {
                return string.Format("CustomerId = {0}, OrderDate = {1}, Total = {2}",
                   this.CustomerId, this.OrderDate, this.Total);
            }
        }
    }
}

 

主程式 && 結果 : GetOrder() 這個方法與引入組件只在遞增排序的範例中顯示

遞增排序範例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            //使用一般排序 預設為遞增
            Program.OrderBy(order, x => x.CustomerId);
            Console.ReadLine();
        }

        /// <summary>
        /// 這是一般排序 後面是要選擇的欄位
        /// </summary>
        private void OrderBy(List<Model1.Order> ob, Expression<Func<Model1.Order, object>> express)
        {
            Console.WriteLine("這是一般排序 後面是要選擇的欄位:  " + express);
            Console.WriteLine("####Linq Syntax: data.OrderBy(ob => ob.columnName);");
            var query = ob.AsQueryable().OrderBy(express);
            query.ToList().ForEach(x => {
                Console.WriteLine(x.ToString());
            });
            Console.WriteLine();
        }

        // 產生模型的假資料,並列印出來。
        private List<Model1.Order> GetOrder()
        {
            var result = new List<Model1.Order> {
                new Model1.Order{CustomerId = 3, OrderDate = new DateTime(2011, 10, 9), Total = 2940},
                new Model1.Order {CustomerId = 2, OrderDate = new DateTime(2012, 10, 10), Total = 3849},
                new Model1.Order {CustomerId = 1, OrderDate = new DateTime(2011, 12, 1), Total = 500},
                new Model1.Order {CustomerId = 1, OrderDate = new DateTime(2012, 2, 28), Total = 1234},
                new Model1.Order {CustomerId = 2, OrderDate = new DateTime(2012, 5, 20), Total = 9520}
            };

            Console.WriteLine("原始------------------資料");
            var i = 1;
            result.ForEach(x => {
                Console.WriteLine("第" + i.ToString() + "筆 " + x.ToString());
                i += 1;
            });
            Console.WriteLine("原始--------------------資料");
            Console.WriteLine();
            return result;
        }
    }   
}

 

遞減排序範例
namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            //使用遞減排序
            Program.OrderByDescending(ob: order, express: x => x.CustomerId);
            Console.ReadLine();
        }

        /// <summary>
        /// 遞減排序
        /// </summary>
        private void OrderByDescending(List<Model1.Order> ob,
           Expression<Func<Model1.Order, object>> express)
        {
            Console.WriteLine("這是遞減排序 後面是要選擇的欄位:  " + express);
            Console.WriteLine("####Linq Syntax: data.OrderByDescending(ob => ob.columnName);");
            var query = ob.AsQueryable().OrderByDescending(express);
            query.ToList().ForEach(x => {
                Console.WriteLine(x.ToString());
            });
            Console.WriteLine();
        }
    }
}

 

多欄位排序範例
namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            //使用多欄位排序
            Program.ThenBy(order, x => x.CustomerId, x => x.OrderDate);
            Console.ReadLine();
        }

        /// <summary>
        /// 多欄位遞增排序
        /// 可輸入 N 個委派運算式
        /// </summary>
        private void ThenBy(List<Model1.Order> ob, Expression<Func<Model1.Order, object>> express,
            params Expression<Func<Model1.Order, object>>[] nExpress)
        {
            Console.WriteLine("這是多欄位遞增排序 後面是要選擇的欄位:  " + express + ", express..: ");
            nExpress.ToList().ForEach(x => Console.WriteLine(x.ToString()));
            Console.WriteLine("####Linq Syntax: data.OrderBy(ob => ob.columnName)." +
                "ThenBy(ob => ob.columnName);");
            var query = ob.AsQueryable().OrderBy(express);
            if (nExpress != null)
            {
                foreach (var item in nExpress)
                {
                    query = query.ThenBy(item);
                }
            }
            query.ToList().ForEach(x => {
                Console.WriteLine(x.ToString());
            });
            Console.WriteLine();
        }
    }
}

 

條件篩選後取第一筆資料
namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            //條件篩選後取第一筆資料
            Program.FirstOrDefault(order, x => x.CustomerId == 2);
            Console.ReadLine();
        }

        /// <summary>
        /// 這是條件篩選後選擇第一筆資料資料,若找無資料則回傳 Null
        /// </summary>
        private void FirstOrDefault(List<Model1.Order> ob, Expression<Func<Model1.Order, bool>> express)
        {
            Console.WriteLine("這是條件篩選後選擇第一筆資料資料 後面是條件:  " + express);
            Console.WriteLine("####Linq Syntax: data.FirstOrDefault(ob => ob.columnName==條件);");
            var query = ob.AsQueryable().FirstOrDefault(express);
            Console.WriteLine(query.ToString() ?? "null"); // 若為 null 則 "null"
            Console.WriteLine();
        }

    }
}

 

 

條件篩選後依索引值選取資料
namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            // 使用索引直選取資料
            Program.ElementAtOrDefault(order, 3);
            Console.ReadLine();
        }

        /// <summary>
        /// 依索引值選取資料
        /// </summary>
        private void ElementAtOrDefault(List<Model1.Order> ob, int index)
        {
            Console.WriteLine("選擇第 " + index + " 筆的資料");
            Console.WriteLine("####Linq Syntax: data.ElementAtOrDefault(index);");
            var query = ob.AsQueryable().ElementAtOrDefault(index);
            Console.WriteLine(query.ToString() ?? "null");
            Console.WriteLine();
        }

    }
}

 

 

撈取資料來源只能為一筆或無資料,倘若大於一筆則拋出例外
namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            // 撈取資料來源只能為一筆或無資料,倘若大於一筆拋出例外
            Program.SingleOrDefault(order, x => x.CustomerId == 2);
            Console.ReadLine();
        }

        /// <summary>
        /// 這是撈取資料來源只能為一筆或無資料
        /// </summary>
        private void SingleOrDefault(List<Model1.Order> ob, Expression<Func<Model1.Order, bool>> express)
        {
            Console.WriteLine("這是撈取資料來源只能為一筆或無資料 否則拋出例外 後面是要選擇的欄位:  " + express);
            Console.WriteLine("####Linq Syntax: data.SingleOrDefault(ob => ob.columnName==條件);");
            try
            {
                var query = ob.AsQueryable().SingleOrDefault(express);
                Console.WriteLine(query.ToString() ?? "null");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Console.WriteLine();
        }

    }
}

 

 

條件篩選後判斷有無資料
namespace LinqDay1
{
    class Program
    {
        static void Main(string[] args)
        {
            var Program = new Program();
            var order = Program.GetOrder();

            // 條件篩選後判斷有無資料
            Program.Any(order, x => x.CustomerId == 5);
            Console.ReadLine();
        }

        #region 判斷有無資料 回傳bool 在只判定有無資料時可使用
        /// <summary>
        /// 條件篩選後確認有無資料 無資料則回傳false 反之true
        /// 若不給條件則判定裡面有無資料
        /// </summary>
        private void Any(List<Model1.Order> ob, Expression<Func<Model1.Order, bool>> express)
        {
            Console.WriteLine("條件篩選後確認有無資料 無資料則回傳false反之true: :  " + express);
            Console.WriteLine("####Linq Syntax: data.Any(ob => ob.columnName==條件);");
            var query = ob.AsQueryable().Any(express);
            Console.WriteLine(query ? query + "有資料" : query + " 無資料"); // if true 為 : 左邊 反之為右
            Console.WriteLine();
        }
        #endregion
    }
}

 

 


多多指教!! 歡迎交流!!

你不知道自己不知道,那你會以為你知道