11. 元素操作符—【LINQ标准查询操作符】
public class DefaultIfEmpty_LINQ { static string ContextString = System.Configuration.ConfigurationSettings.AppSettings["ContextString"].ToString(); static DataContext context = new DataContext(ContextString); static Table<Contact> contact = context.GetTable<Contact>(); // 这些操作符用于实现了IEnumerable<T>接口的类型 public static void DefaultIfEmpty_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Z") select c.FirstName; foreach (string item in query.DefaultIfEmpty()) { Console.WriteLine(item.ToString()); } var query2 = from c in contact where c.FirstName.StartsWith("ZZ") select c.FirstName; foreach (string item in query2.AsEnumerable().DefaultIfEmpty("none")) { Console.WriteLine(item.ToString()); } } public static void ElementAt_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Z") select c.FirstName; Console.WriteLine(query.ElementAt(0)); } public static void ElementAtOrDefault_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Z") select c.FirstName; Console.WriteLine(query.ElementAtOrDefault(50000)); } public static void First_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Z") select c.FirstName; Console.WriteLine(query.First()); } public static void Last_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Z") select c.FirstName; Console.WriteLine(query.Last()); } public static void FirstOrDefault_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Zs") select c.FirstName; Console.WriteLine(query.FirstOrDefault()); } public static void LastOrDefault_Print() { IEnumerable<string> query = from c in contact where c.FirstName.StartsWith("Za") select c.FirstName; Console.WriteLine(query.LastOrDefault()); } public static void Single_Print() { IEnumerable<string> query = from c in contact where c.ContactID.Equals(20) select c.FirstName; Console.WriteLine(query.Single()); IEnumerable<int> query2 = from c in contact select c.ContactID; Console.WriteLine(query2.Single(c=>c.Equals(10))); } public static void SingleOrDefault_Print() { IEnumerable<string> query = from c in contact where c.LastName.Equals("Kobylinski") select c.FirstName; Console.WriteLine(query.SingleOrDefault()); } }
【天天来(http://www.daydaycome.com)】- 精选折扣商品,爆料精选,九块九白菜底价尽在天天来!是一个中立的,致力于帮助广大网友买到更有性价比网购产品的分享平台,每天为网友们提供最受追捧 最具性价比 最大幅降价潮流新品资讯。我们的信息大部分来自于网友爆料,如果您发现了优质的产品或好的价格,不妨给我们爆料(谢绝商家)