/// <summary> /// LINQ SELECT結果放入匿名型別Object,並指定參數加入運算 /// </summary> public static void selectResultToClassObject() { using (var context = new LunchBoxModel()) { //查詢SELECT IEnumerable <SProduct> products = from product in context.Product select new SProduct() { PId = product.Id.ToString(), SName = product.Category + "-" + product.Name, Price = product.Price, SPrice = product.Price * 0.8 }; foreach (var p in products) { Console.WriteLine( "{0}\t定價:{1}\t特價:{2}\t:{3}", p.PId, p.Price, p.SPrice, p.SName ); } } }
/// <summary> /// LINQ SELECT基本查詢 /// </summary> public static void select() { using (var context = new LunchBoxModel()) { //查詢SELECT IQueryable <Product> products = from product in context.Product select product; foreach (Product p in products) { Console.WriteLine( "分類:{0}\t{1}\t{2}\t價格:{2}\t", p.Category, p.Id, p.Name, p.Price ); } } }
/// <summary> /// LINQ SELECT結果放入匿名型別Object /// </summary> public static void selectResultToAnonyObject() { using (var context = new LunchBoxModel()) { //查詢SELECT var products = from product in context.Product select new { product.Name, product.Price }; foreach (var p in products) { Console.WriteLine( "分類:{0}\t{1}", p.Price, p.Name ); } } }
/// <summary> /// LINQ SELECT結果放入匿名型別Object,並指定參數加入運算 /// </summary> public static void selectResultToAnonyObject2() { using (var context = new LunchBoxModel()) { //查詢SELECT var products = from product in context.Product select new { ProductName = product.Name, Price = product.Price, SPrict = product.Price * 0.8 }; foreach (var p in products) { Console.WriteLine( "分類:{0}\t特價:{1}\t商品:{2}", p.Price, p.SPrict, p.ProductName ); } } }
static void Main(string[] args) { //建立DB連線Object LunchBoxModel db = new LunchBoxModel(); //取得DB Product Table內容筆數 int count = db.Product.Count(); Console.WriteLine("Table Count: " + count); //取得DB Product Table所有內容 IEnumerable <Product> data = db.Product.Select(x => x); //列出Product Table內容 foreach (Product p in data) { //id int id = p.Id; //name string name = p.Name; //price int?price = p.Price; //category int category = p.Category; //顯示 Console.WriteLine("{3}\t訂單:{2}\t{0}\t{1}", id, name, price, category); } LinqDepiction.select(); LinqDepiction.selectResultToAnonyObject(); LinqDepiction.selectResultToAnonyObject2(); LinqDepiction.selectResultToClassObject(); LinqDepiction.selectNestedArray(); Console.ReadKey(); }