10. 转换操作符—【LINQ标准查询操作符】
public class AsEnumerable_LINQ { static string ContextString = System.Configuration.ConfigurationSettings.AppSettings["ContextString"].ToString(); static DataContext context = new DataContext(ContextString); static Table<Contact> contacts = context.GetTable<Contact>(); public static void AsEnumerable_Print() { IEnumerable<Contact> query = contacts.AsEnumerable().Where(con => con.FirstName.StartsWith("K")); foreach (var item in query) { Console.WriteLine(item.FirstName); } } public static void Cast_Print() { /* * 利用Cast将IEnumerable集合中的元素转换为某种指定的类型,这样做的好处是通过提供必要的类型信息 * 可以将标准查询操作符应用于非泛型集合之上 */ ArrayList names = new ArrayList(); names.Add("Alex"); names.Add("Jack"); names.Add("Miles"); names.Add("Hugo"); names.Add("Ben"); IEnumerable<string> query = names.Cast<string>().Select(name => name); foreach (var item in query) { Console.WriteLine(item.ToString()); } } public static void OfType_Print() { ArrayList names = new ArrayList(); names.Add("Alex"); names.Add("Jack"); names.Add("Miles"); names.Add("Hugo"); names.Add("Ben"); names.Add(12); names.Add(3); names.Add(20); names.Add(83); IEnumerable<int> query = names.OfType<int>().Select(name => name); foreach (int item in query) { Console.WriteLine(item.ToString()); } } public static void ToArray_Print() { var query = contacts.Select(con => con.FirstName).ToArray(); foreach (string s in query) { Console.WriteLine(s.ToString()); } } public static void ToDictionary_Print() { Dictionary<string, Contact> dic = contacts.ToDictionary(con => con.EmailAddress); foreach (KeyValuePair<string,Contact> item in dic) { Console.WriteLine(item.Value.FirstName + " " + item.Value.LastName + " " + item.Key); } } public static void ToList_Print() { var query = (from c in contacts select c.FirstName).ToList(); foreach (var item in query.Take(10)) { Console.WriteLine(item.ToString()); } } public static void ToLookUp_Print() { ILookup<string, string> lookUp = contacts.ToLookup(con => con.FirstName, con => con.MiddleName + " " + con.LastName); foreach (IGrouping<string,string> item in lookUp) { Console.WriteLine(item.Key); foreach (var i in item) { Console.WriteLine(" " + i.ToString()); } } } }
【天天来(http://www.daydaycome.com)】- 精选折扣商品,爆料精选,九块九白菜底价尽在天天来!是一个中立的,致力于帮助广大网友买到更有性价比网购产品的分享平台,每天为网友们提供最受追捧 最具性价比 最大幅降价潮流新品资讯。我们的信息大部分来自于网友爆料,如果您发现了优质的产品或好的价格,不妨给我们爆料(谢绝商家)