101 LINQ Samples: Element Operators

First - Simple

This sample uses First to return the first matching element as a Product, instead of as a sequence containing a Product.

public void Linq58() {     List<Product> products = GetProductList();       Product product12 = (         from p in products         where p.ProductID == 12         select p)         .First();       ObjectDumper.Write(product12); }

Result

ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86

First - Condition

This sample uses First to find the first element in the array that starts with 'o'.


public void Linq59() {     string[] strings = { "zero""one""two""three""four""five""six""seven""eight""nine" };       string startsWithO = strings.First(s => s[0] == 'o');       Console.WriteLine("A string starting with 'o': {0}", startsWithO); }

Result

A string starting with 'o': one

FirstOrDefault - Simple

This sample uses FirstOrDefault to try to return the first element of the sequence, unless there are no elements, in which case the default value for that type is returned.

public void Linq61() {     int[] numbers = { };       int firstNumOrDefault = numbers.FirstOrDefault();       Console.WriteLine(firstNumOrDefault); }

Result

0

FirstOrDefault - Condition

This sample uses FirstOrDefault to return the first product whose ProductID is 789 as a single Product object, unless there is no match, in which case null is returned.

public void Linq62() {     List<Product> products = GetProductList();       Product product789 = products.FirstOrDefault(p => p.ProductID == 789);       Console.WriteLine("Product 789 exists: {0}", product789 != null); }

Result

Product 789 exists: False

ElementAt

This sample uses ElementAt to retrieve the second number greater than 5 from an array.

public void Linq64() {     int[] numbers = { 5413986720 };       int fourthLowNum = (         from n in numbers         where n > 5         select n)         .ElementAt(1);  // second number is index 1 because sequences use 0-based indexing       Console.WriteLine("Second number > 5: {0}", fourthLowNum); }

Result

Second number > 5: 8

转载于:https://www.cnblogs.com/zjz008/archive/2011/03/13/1982924.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值