1. 投影操作符—【LINQ标准查询操作符】
public class Select_LINQ { public static string ContextString = System.Configuration.ConfigurationSettings.AppSettings["ContextString"].ToString(); public static void Print() { DataContext context = new DataContext(ContextString); Table<Contact> contact = context.GetTable<Contact>(); var querySyntex = from c in contact where c.FirstName.StartsWith("S") select new { c.FirstName, c.LastName, c.EmailAddress }; var methodSyntex = contact.Select(c => new { c.FirstName, c.LastName, c.EmailAddress }).Where(con => con.FirstName.StartsWith("S")); Console.WriteLine("============== Query Syntex =============="); foreach (var item in querySyntex.Take(10)) { Console.WriteLine(item.ToString()); } Console.WriteLine("\n"); Console.WriteLine("============== Method Syntex =============="); foreach (var item in methodSyntex.Take(10)) { Console.WriteLine(item.ToString()); } Console.ReadKey(); } } public class SelectMany_LINQ { public static void Print() { Names[] names = { new Names{FirstName = "J. Phillip",Pets = new List<string>{"Yudon","Fido"}}, new Names{FirstName = "Michelle",Pets = new List<string>{"Alexander","Alcorn"}}, new Names{FirstName = "Maxwell",Pets = new List<string>{"Alpuerto","Arakawa"}} }; IEnumerable<string> nameQuery = names.AsQueryable().SelectMany(n => n.Pets); //List<string> list = nameQuery.ToList<string>();// 立即执行 foreach (var item in nameQuery) { Console.WriteLine(item); } Console.WriteLine("\n"); // 注意nameQuery 与 nameQuery2 的区别 /* * IEnumerable接口提供了向前遍历的功能,它不具有在各个数据项之间移动(向前移动除外)的能力 * 然而,IQueryable可以可以使查询操作更具灵活性,虽然是IQueryable实现了IEnumerable,但IEnumerable * 为IQueryable提供了遍历功能。 */ IQueryable nameQuery2 = names.AsQueryable().Select(n => n); foreach (var item in nameQuery2) { Console.WriteLine(((Names)item).FirstName); foreach (var p in ((Names)item).Pets) { Console.WriteLine(" " + p.ToString()); } } Console.ReadKey(); } } struct Names { public string FirstName; public List<string> Pets; }
【天天来(http://www.daydaycome.com)】- 精选折扣商品,爆料精选,九块九白菜底价尽在天天来!是一个中立的,致力于帮助广大网友买到更有性价比网购产品的分享平台,每天为网友们提供最受追捧 最具性价比 最大幅降价潮流新品资讯。我们的信息大部分来自于网友爆料,如果您发现了优质的产品或好的价格,不妨给我们爆料(谢绝商家)