重视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()
 
//2、Combining Interpreted and Local Queries
void Main()
{
//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;
                  }
             }
     }
}
image

 //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();

posted on 2012-03-01 22:53  Sanic  阅读(152)  评论(0编辑  收藏  举报

导航