LINQ is a cool feature in C# 3.0. Most of the developers are struggling for the syntax and examples. Here I have collected various examples for each operator in LINQ and the equivalent Lambda Expressions.

Where

IEnumerable<Product>
x = products.Where(p => p.UnitPrice >= 10);

IEnumerable<Product> x =
    from p in products
    where p.UnitPrice >= 10
    select p;

Select

IEnumerable<string>
productNames = products.Select(p => p.Name);

IEnumerable<string> productNames =
from p in
products select p.Name;

var
namesAndPrices =
    products.
    Where(p => p.UnitPrice >= 10).
    Select(p => new { p.Name, p.UnitPrice }).
    ToList();
IEnumerable<int>
indices =
    products.
    Select((product, index) => new { product,
index }).
    Where(x => x.product.UnitPrice >= 10).
    Select(x => x.index);

SelectMany

IEnumerable<Order>
orders =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders);
var namesAndOrderIDs =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    Select(o => new { o.Customer.Name, o.OrderID
});
var namesAndOrderIDs =
    customers.
    Where(c => c.Country == "Denmark").
    SelectMany(c => c.Orders, (c,o) => new { c, o }).
    Where(co => co.o.OrderDate.Year == 2005).
    Select(co => new { co.c.Name, co.o.OrderID
});

var
namesAndOrderIDs =
    from c in customers
    where c.Country == "Denmark"
    from o in c.Orders
    where o.OrderDate.Year == 2005
    select new { c.Name, o.OrderID };

Take

IEnumerable<Product>
MostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Take(10);

Skip

IEnumerable<Product>
AllButMostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Skip(10);

TakeWhile SkipWhile

s.TakeWhile(p)s.SkipWhile(p)

Join

var custOrders =
    customers.
    Join(orders, c => c.CustomerID, o => o.CustomerID,
        (c, o) => new { c.Name, o.OrderDate,
o.Total }
    );
var custOrders =
    from c in customers
    join o in orders
on c.CustomerID equals
o.CustomerID
    select new { c.Name, o.OrderDate,
o.Total };

GroupJoin

var custTotalOrders =
    customers.
    GroupJoin(orders, c => c.CustomerID, o => o.CustomerID,
        (c, co) => new { c.Name, TotalOrders =
co.Sum(o => o.Total) }
    );
var custTotalOrders =
    from c in customers
    join o in orders
on c.CustomerID equals
o.CustomerID into co
    select new { c.Name, TotalOrders =
co.Sum(o => o.Total) };
var custTotalOrders =
    from c in customers
    join o in orders
on c.CustomerID equals
o.CustomerID
    select new { c.Name, o.OrderDate,
o.Total };
var custTotalOrders =
    from c in customers
    join o in orders
on c.CustomerID equals
o.CustomerID into co
    from o in co
    select new { c.Name, o.OrderDate,
o.Total };
var custTotalOrders =
    from c in customers
    join o in orders
on c.CustomerID equals
o.CustomerID into co
    from o in
co.DefaultIfEmpty(emptyOrder)
    select new { c.Name, o.OrderDate,
o.Total };

Concat

IEnumerable<string>
locations =
    customers.Select(c => c.City).
    Concat(customers.Select(c => c.Region)).
    Concat(customers.Select(c => c.Country)).
    Distinct();

IEnumerable<string> locations =
    new[] {
        customers.Select(c => c.City),
        customers.Select(c => c.Region),
        customers.Select(c => c.Country),
    }.
    SelectMany(s => s).
    Distinct();

OrderBy / ThenBy

IEnumerable<Product>
orderedProducts1 =
    products.
    OrderBy(p => p.Category).
    ThenByDescending(p => p.UnitPrice).
    ThenBy(p => p.Name);
IEnumerable<Product>
orderedProducts1 =
    from p in products
    orderby p.Category, p.UnitPrice descending,
p.Name
    select p;
IEnumerable<Product>
orderedProducts2 =
    products.
    Where(p => p.Category == "Beverages").
    OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
IEnumerable<string>
orderedProductNames =
    products.
    Where(p => p.Category == "Beverages").
    Select(p => p.Name).
    OrderBy(x => x);

GroupBy

IEnumerable<IGrouping<string,
Product>> productsByCategory =
    products.GroupBy(p => p.Category);
IEnumerable<IGrouping<string,
string>> productNamesByCategory =
    products.GroupBy(p => p.Category, p => p.Name);

Distinct

IEnumerable<string>
productCategories =
    products.Select(p => p.Category).Distinct();

AsEnumerable

Table<Customer> custTable = GetCustomersTable();
var query = custTable.AsEnumerable().Where(c =>
IsGoodCustomer(c));

ToArray

string[] customerCountries =
    customers.Select(c => c.Country).Distinct().ToArray();

ToList

List<Customer>
customersWithOrdersIn2005 =
    customers.
    Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
    ToList();

ToDictionary

Dictionary<int,Order>
orders =
    customers.
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    ToDictionary(o => o.OrderID);
Dictionary<string,decimal>
categoryMaxPrice =
    products.
    GroupBy(p => p.Category).
    ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));

ToLookup

Lookup<string,Product> productsByCategory
=
    products.ToLookup(p => p.Category);
IEnumerable<Product>
beverages = productsByCategory["Beverage"];

OfType

List<Person>
persons = GetListOfPersons();
IEnumerable<Employee>
employees = persons.OfType<Employee>();

Cast

ArrayList objects = GetOrders();
IEnumerable<Order>
ordersIn2005 =
    objects.
    Cast<Order>().
    Where(o => o.OrderDate.Year == 2005);
ArrayList objects = GetOrders();
IEnumerable<Order>
ordersIn2005 =
    from Order o in objects
    where o.OrderDate.Year == 2005
    select o;

First

string phone = "206-555-1212";
Customer c = customers.First(c => c.Phone ==
phone);

Single

int id = 12345;
Customer c = customers.Single(c => c.CustomerID
== id);

ElementAt

Product thirdMostExpensive =
    products.OrderByDescending(p => p.UnitPrice).ElementAt(2);

Range

int[] squares =
Enumerable.Range(0, 100).Select(x => x * x).ToArray();

Repeat

long[] x = Enumerable.Repeat(-1L,
256).ToArray();

Empty

IEnumerable<Customer>
noCustomers = Enumerable.Empty<Customer>();

Any

bool b = products.Any(p => p.UnitPrice >= 100 &&
p.UnitsInStock == 0);

All

IEnumerable<string>
fullyStockedCategories =
    products.
    GroupBy(p => p.Category).
    Where(g => g.Group.All(p => p.UnitsInStock > 0)).
    Select(g => g.Key);

Count

int count = customers.Count(c => c.City ==
"London");

Sum

int year = 2005;
var namesAndTotals =
    customers.
    Select(c => new {
        c.Name,
        TotalOrders =
            c.Orders.
            Where(o => o.OrderDate.Year == year).
            Sum(o => o.Total)
    });

Min

var minPriceByCategory =
    products.
    GroupBy(p => p.Category).
    Select(g => new {
        Category = g.Key,
        MinPrice = g.Group.Min(p => p.UnitPrice)
    });

Max

decimal largestOrder =
    customers.
    SelectMany(c => c.Orders).
    Where(o => o.OrderDate.Year == 2005).
    Max(o => o.Total);

Average

var averageOrderTotals =
    customers.
    Select(c => new {
        c.Name,
        AverageOrderTotal = c.Orders.Average(o => o.Total)
    });

Aggregate

var
longestNamesByCategory =
    products.
    GroupBy(p => p.Category).
    Select(g => new {
        Category = g.Key,
        LongestName =
            g.Group.
            Select(p => p.Name).
            Aggregate((s,
t) => t.Length > s.Length ? t : s)
    });

http://www.c-sharpcorner.com/uploadfile/babu_2082/linq-operators-and-lambda-expression-syntax-examples

LINQ LINQ Operators and Lambda Expression - Syntax & Examples的更多相关文章

  1. Linq to Sql : 动态构造Expression进行动态查询

    原文:Linq to Sql : 动态构造Expression进行动态查询 前一篇在介绍动态查询时,提到一个问题:如何根据用户的输入条件,动态构造这个过滤条件表达式呢?Expression<Fu ...

  2. Part 99 Lambda expression in c#

    class Program { static void Main(string[] args) { List<Person> persons = new List<Person> ...

  3. Lambda Expression in C#

    1.Expression Expression<Func<double, double>> exp = a => Math.Sin(a); 委托类型Func<dou ...

  4. C++ lambda expression

    Emerged since c++11, lambda expression/function is an unnamed function object capable of capturing v ...

  5. hdu 1031 (partial sort problem, nth_element, stable_partition, lambda expression) 分类: hdoj 2015-06-15 17:47 26人阅读 评论(0) 收藏

    partial sort. first use std::nth_element to find pivot, then use std::stable_partition with the pivo ...

  6. 浅析Java 8新特性Lambda Expression

    什么是Lambda Expression 对于Lambda Expression,我的理解是,它是一个函数表达式,如下: (int x, int y) -> x - y 符号左边定义了函数的输入 ...

  7. Lambda Expression

    Java 8的一个大亮点是引入Lambda表达式,使用它设计的代码会更加简洁.当开发者在编写Lambda表达式时,也会随之被编译成一个函数式接口.下面这个例子就是使用Lambda语法来代替匿名的内部类 ...

  8. Variable used in lambda expression should be final or effectively final

    Lambda与匿名内部类在访问外部变量时,都不允许有修改变量的倾向,即若: final double a = 3.141592; double b = 3.141592; DoubleUnaryOpe ...

  9. JDK 8 - Lambda Expression 的优点与限制

    我们知道 JDK 8 新增了 Lambda Expression 这一特性. JDK 8 为什么要新增这个特性呢? 这个特性给 JDK 8 带来了什么好处? 它可以做什么?不可以做什么? 在这篇文章, ...

随机推荐

  1. 第十一周PSP

    第十一周PSP   工作周期:11.24-12.1  本周PSP: C类型 C内容 S开始时间 ST结束时间 I中断时间 T净时间(分) 11月29 文档 写随笔 19:00min 19:30min ...

  2. ORACLE 日常处理办法

    Oracle删除当前用户下所有的表的方法 1.如果有删除用户的权限,则可以: drop user user_name cascade; 加了cascade就可以把用户连带的数据全部删掉. 删除后再创建 ...

  3. keepalived+mysql实现双主高可用

    环境: DB1:centos6.8.mysql5.5.192.168.2.204  hostname:bogon DB2:centos6.8.mysql5.5.192.168.2.205  hostn ...

  4. My安卓知识2--使用listview绑定sqlite中的数据

    我想在我的安卓项目中实现一个这样的功能,读取sqlite数据库中的数据并显示到某个页面的listview控件中. 首先,我建立了一个Service类,来实现对数据库的各种操作,然后在这个类中添加对数据 ...

  5. Android Studio使用JNI和NDK进行开发

    想要学习一下在Android Studio中进行JNI的开发,文章挺多的,但是几乎没有一个完整的说明的,中间总是有一两步漏掉.分享技术就应该完整的让读者学会,藏着掖着不是君子所为.对于那些故意含糊过去 ...

  6. interactivePopGestureRecognizer属性

    苹果一直都在人机交互中尽力做到极致,在iOS7中,新增加了一个小小的功能,也就是这个api:self.navigationController.interactivePopGestureRecogni ...

  7. Spring+struts2的基础上继续加hibernate3的jar包

  8. css3之文本新属性

                                                     

  9. 浅论ViewController的加载 -- 解决 viewDidLoad 被提前加载的问题(pushViewController 前执行)

    一个ViewController,一般通过init或initWithNibName来加载.二者没有什么不同,init最终还是要调用initWithNibName方法(除非这个ViewControlle ...

  10. JSTL和EL表达式多重if问题

    俾人以前在写一个查询功能时,由于结果状态分好几种,于是页面就用<c:if></c:if>写了一大堆来判断,后来上网查了下资料,发现有个语法类似于多重if,挺方便的,语法是 &l ...