重视Linq技术_3
Interpreted Queries
//1、Simple LINQ to SQL Query
from c in Customers
where c.Name.Contains ("a")
orderby c.Name.Length
select c.Name.ToUpper()
where c.Name.Contains ("a")
orderby c.Name.Length
select c.Name.ToUpper()
//2、Combining Interpreted and Local Queries
void Main()
{
//This uses a custom 'Pair' extension method, defined below.
{
//This uses a custom 'Pair' extension method, defined below.
IEnumerable<string> q = Customers
.Select (c => c.Name.ToUpper())
.Pair() // Local from this point on.
.OrderBy (n => n);
q.Dump();
}
public static class MyExtensions
{
public static IEnumerable<string> Pair (this IEnumerable<string> source)
{
string firstHalf = null;
foreach (string element in source)
{
if (firstHalf == null)
{
firstHalf = element;
}
else
{
yield return firstHalf + ", " + element;
firstHalf = null;
}
}
}
}
.Select (c => c.Name.ToUpper())
.Pair() // Local from this point on.
.OrderBy (n => n);
q.Dump();
}
public static class MyExtensions
{
public static IEnumerable<string> Pair (this IEnumerable<string> source)
{
string firstHalf = null;
foreach (string element in source)
{
if (firstHalf == null)
{
firstHalf = element;
}
else
{
yield return firstHalf + ", " + element;
firstHalf = null;
}
}
}
}
![image image](https://images.cnblogs.com/cnblogs_com/sanic/201203/201203012252269038.png)
//3、Regex in LINQ to SQL query
// The following query throws an exception, because Regex has no equivalent in SQL:
Regex wordCounter = new Regex (@"\b(\w|[-'])+\b");
var query = MedicalArticles
.Where (article => article.Topic == "influenza"
&& wordCounter.Matches (article.Abstract).Count < 100);
query.Dump();
//Expression for right
Regex wordCounter = new Regex (@"\b(\w|[-'])+\b");
var query = MedicalArticles
.Where (article => article.Topic == "influenza")
.AsEnumerable()
.Where (article => wordCounter.Matches (article.Abstract).Count < 100);
query.Dump();
Regex wordCounter = new Regex (@"\b(\w|[-'])+\b");
var query = MedicalArticles
.Where (article => article.Topic == "influenza"
&& wordCounter.Matches (article.Abstract).Count < 100);
query.Dump();
//Expression for right
Regex wordCounter = new Regex (@"\b(\w|[-'])+\b");
var query = MedicalArticles
.Where (article => article.Topic == "influenza")
.AsEnumerable()
.Where (article => wordCounter.Matches (article.Abstract).Count < 100);
query.Dump();