LINQ LINQ Operators and Lambda Expression - Syntax & Examples
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的更多相关文章
- Linq to Sql : 动态构造Expression进行动态查询
原文:Linq to Sql : 动态构造Expression进行动态查询 前一篇在介绍动态查询时,提到一个问题:如何根据用户的输入条件,动态构造这个过滤条件表达式呢?Expression<Fu ...
- Part 99 Lambda expression in c#
class Program { static void Main(string[] args) { List<Person> persons = new List<Person> ...
- Lambda Expression in C#
1.Expression Expression<Func<double, double>> exp = a => Math.Sin(a); 委托类型Func<dou ...
- C++ lambda expression
Emerged since c++11, lambda expression/function is an unnamed function object capable of capturing v ...
- 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 ...
- 浅析Java 8新特性Lambda Expression
什么是Lambda Expression 对于Lambda Expression,我的理解是,它是一个函数表达式,如下: (int x, int y) -> x - y 符号左边定义了函数的输入 ...
- Lambda Expression
Java 8的一个大亮点是引入Lambda表达式,使用它设计的代码会更加简洁.当开发者在编写Lambda表达式时,也会随之被编译成一个函数式接口.下面这个例子就是使用Lambda语法来代替匿名的内部类 ...
- Variable used in lambda expression should be final or effectively final
Lambda与匿名内部类在访问外部变量时,都不允许有修改变量的倾向,即若: final double a = 3.141592; double b = 3.141592; DoubleUnaryOpe ...
- JDK 8 - Lambda Expression 的优点与限制
我们知道 JDK 8 新增了 Lambda Expression 这一特性. JDK 8 为什么要新增这个特性呢? 这个特性给 JDK 8 带来了什么好处? 它可以做什么?不可以做什么? 在这篇文章, ...
随机推荐
- [刘阳Java]_避开环境配置快速的使用Java的开发工具_第5讲
我们一般学习Java都应该遵循通过系统的命令工具来编译Java程序,然后对编译好Java程序进行运行,这个是非常好的习惯.但是随着后期学习Java技术的深入我们也得像Java的IDE工具屈服.所以,可 ...
- 模糊测试(Fuzz testing)
模糊测试(fuzz testing)是一种安全测试方法,他介于完全的手工测试和完全的自动化测试之间.为什么是介于那两者之间?首先完全的手工测试即是渗透测试,测试人员可以模拟黑客恶意进入系统.查找漏洞, ...
- 3.使用git提交项目到开源中国(gitosc)
1.提交地址 使用的是开源中国git仓库 git.oschina.net 在windos环境下使用msysgit. 2.初始化化 username.email初始化 git config --glob ...
- Netty 的 inbound 与 outbound, 以及 InboundHandler 的 channelInactive 与 OutboundHandler 的 close
先看一个例子. 有一个简单 Server public class SimpleServer { public static void main(String[] args) throws Excep ...
- SQL Server 查询所有外键子父表关系
SELECT table_name,fk_name,reference_table_name,fk_list_number,fk_detailFROM (SELECT object_name(f.ob ...
- apktool+dex2jar+xjad反编译android程序
1 将MyAdroid.apk拷贝到E:\disapk 2 下载apktool1.5.2.tar.bz2 和 apktool-install-windows-r05-ibot.tar.bz2 并解压到 ...
- 火狐通行证升级为Firefox Sync后,如何在多设备间同步书签等信息
一直在使用Firefox的一个比较重要的原因是习惯了它的书签同步功能,之前一直是使用火狐通行证来实现多设备间同步的,最近新装了WIN8.1系统来学习,结果装上新版Firefox之后,发现无论怎么弄也没 ...
- en_windows_10_multiple_editions_version_1511_x64.iso
好久没折腾电脑了,这几天在E盘装了个64位Windows 10 TH2 专业版,从MSDN官网下载的英文原版镜像,用kms10未能激活,一看日志文件,说我这是零售版,后面就关掉了什么监听端口,然后就完 ...
- Oracle数据库导入导出命令总结 (详询请加qq:2085920154)
分类: Linux Oracle数据导入导出imp/exp就相当于oracle数据还原与备份.exp命令可以把数据从远程数据库服务器导出到本地的dmp文件,imp命令可以把dmp文件从本地导入到远处的 ...
- Android Webview 调用JS跳转到指定activity
JAVA: WebView wv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(save ...