有时候已知一个 ID 的数组,需要读取这些记录内容,SQL 可以联接多个“或”关系去读取,或使用“In”语句,在 LINQ TO SQL 中可以这样来做:
List<int> ids = new List<int> { 1, 2, 3 }; List<string> tbs = db.dbTables.Where(c => ids.Contains<int>(c.ID)).ToList();

BT种子文件使用了一种叫bencoding的编码方法来保存数据。
bencoding现有四种类型的数据:srings(字符串),integers(整数),lists(列表),dictionaries(字典)
编码规则如下:
strings(字符串)编码为:<字符串长度>:<字符串>
例如: 4:test 表示为字符串"test"
4:例子 表示为字符串“例子”
字符串长度单位为字节
没开始或结束标记
integers(整数)编码为:i<整数>e
开始标记i,结束标记为e
例如: i1234e 表示为整数1234
i-1234e 表示为整数-1234
整数没有大小限制
i0e 表示为整数0
i-0e 为非法
以0开头的为非法如: i01234e 为非法
lists(列表)编码为:l<bencoding编码类型>e
开始标记为l,结束标记为e
列表里可以包含任何bencoding编码类型,包括整数,字符串,列表,字典。
例如: l4:test5abcdee 表示为二个字符串["test","abcde"]
dictionaries(字典)编码为d<bencoding字符串><bencoding编码类型>e
开始标记为d,结束标记为e
关键字必须为bencoding字符串
值可以为任何bencoding编码类型
例如: d3:agei20ee 表示为{"age"=20}
d4:path3:C:\8:filename8:test.txte 表示为{"path"="C:\","filename"="test.txt"}
具体文件结构如下:
全部内容必须都为bencoding编码类型。
整个文件为一个字典结构,包含如下关键字
announce:tracker服务器的URL(字符串)
announce-list(可选):备用tracker服务器列表(列表)
creation date(可选):种子创建的时间,Unix标准时间格式,从1970 1月1日 00:00:00到创建时间的秒数(整数)
comment(可选):备注(字符串)
created by(可选):创建人或创建程序的信息(字符串)
info:一个字典结构,包含文件的主要信息,为分二种情况:单文件结构或多文件结构
单文件结构如下:
length:文件长度,单位字节(整数)
md5sum(可选):长32个字符的文件的MD5校验和,BT不使用这个值,只是为了兼容一些程序所保留!(字符串)
name:文件名(字符串)
piece length:每个块的大小,单位字节(整数)
pieces:每个块的20个字节的SHA1 Hash的值(二进制格式)
多文件结构如下:
files:一个字典结构
length:文件长度,单位字节(整数)
md5sum(可选):同单文件结构中相同
path:文件的路径和名字,是一个列表结构,如\test\test.txt 列表为l4:test8test.txte
name:最上层的目录名字(字符串)
piece length:同单文件结构中相同
pieces:同单文件结构中相同
实例:
用记事本打开一个.torrent可以看来类似如下内容
d8:announce35:http://www.manfen.net:7802/announce13:creation datei1076675108e4:infod6:lengthi17799e4:name62:MICROSOFT.WINDOWS.2000.AND.NT4.SOURCE.CODE-SCENELEADER.torrent12:piece lengthi32768e6:pieces20:?W ?躐?緕排T酆ee
很容易看出
announce=http://www.manfen.net:7802/announce
creation date=1076675108秒(02/13/04 20:25:08)
文件名=MICROSOFT.WINDOWS.2000.AND.NT4.SOURCE.CODE-SCENELEADER.torrent
文件大小=17799字节
文件块大小=32768字节
大家知道,Windows Mobile 6.0 SDK自带了cellular emulator和fake GPS,使得我们可以在模拟器上调试radio级的phone call和基于GPS的地理位置应用。前几天,一位MVP Dmitry Klionsky撰写了文章《Bluetooth for Microsoft Device Emulator》,讲述了在Windows Mobile模拟器上使用蓝牙的方法,我觉得这对于开发移动设备上蓝牙通信的朋友来说,是非常有用的。
我们来看看实现Bluetooth的架构,参考图1(来源于Bluetooth for Microsoft Device Emulator),主要包括emulator端和PC端:
图1:Emulator和PC上实现Bluetooth通信的架构
1. Emulator端
Bluetooth HCI Transport Driver
Microsoft Remote Tools Framework remote agent
2. PC端
Microsoft Remote Tools Framework desktop plugin
FreeBT USB Driver runtime
FreeBTUSB Driver
Connected Bluetooth USB device
注意:作者采用了FreeBT这个开源的工程来控制Bluetooth的接入。
在Windows Mobile模拟器上使用蓝牙的必要条件有:
1. Visual studio 2005 with SP1 或者 Visual studio 2008
2. Windows Mobile 5.0 Pocket PC/Smartphone SDK and/or Windows Mobile 6 Standard/Professional SDK emulator images
4. Microsoft Remote Tools Framework 1.00
5. 一个具有USB接口的Bluetooth dongle
在Windows Mobile模拟器上使用蓝牙的步骤如下(详细请参考Bluetooth for Microsoft Device Emulator):
1. 在PC端安装下载的FreeBT的蓝牙驱动,方法自然是通过“windows设备管理器”,为新的硬件设备(也就是连接的Bluetooth USB device)添加下载过来的驱动(主要是找到fbtusb.inf文件)。
2. 在Remote Tools Framework plugin中运行BthEmulManager.cetool,将其和模拟器建立连接。
3. 连接建立以后,蓝牙设备的信息(Address, Manufacturer, HCI Version, LMP Version)就会显示在界面上了,如图2所示(来源于Bluetooth for Microsoft Device Emulator).
图2:建立蓝牙联系以后,在模拟器上的信息
4. Microsoft Remote Tools Framework允许我们同时开启两个模拟器,因此,如果手头有两个Bluetooth USB dongle的话,我们就可以在两个模拟器上调试蓝牙的收发通信了。
参考链接:
Dmitry Klionsky:Bluetooth for Microsoft Device Emulator
MSDN:Bluetooth HCI Transport Driver
MSDN:Serial Port Driver
Open source:FreeBT
支付宝(www.alipay.com)的产生的确对于促进网络支付的确起到了很大的推动作用,笔者就在目前自己使用支付宝API接口开发中,遇到的一些问题,解决办法,做了简短的记录,由此与大家共分享,由于作者水平有限,难免出现错误,请大家指出,谢谢。
目前,申请支付宝接口主要有两种方式,1.免费接口,淘宝抽取手续费2%;2.付费接口,比如600元允许48000元交易金额的配额等,笔者使用的是前者,免费接口。在免费接口中,又分为两种,标准双接口交易类型和即时到账交易,这两种支付方式中,前者为淘宝担保交易+即时到账交易,而后者仅仅为即时到账交易,可根据自己的需要进行申请。
具体申请的过程在这里就不赘述了,如有需要,可以通过留言的方式,我会告知您。
支付接口申请成功后,会的到两个重要的参数支付宝安全校验码(key)和合作伙伴id(partner),这两个参数起到了支付是否成功的重要作用,申请成功后,都可以在支付宝后台商家工具中获得。
支付宝的原理其实就是通过浏览器传参数到支付网关(https://www.alipay.com/cooperate/gateway.do),支付网关是由Struts构建的,笔者感觉是通过ActionForm获得浏览器参数,进行内部解析的,浏览器传的参数都进过了MD5加密处理。
笔者遇到的第一个问题:
HAS_NO_PRIVILEGE,在官方给出的API介绍中是这样解释的:“该错误提示的是,您没有使用该接口的权限,那么登陆自己的支付宝账户,商家工具,查看实物交易服务或者虚拟物品交易服务,如果没有申请,请立刻申请并且当时开通。”我很肯定的是我已经开通了服务,那么问题就不是出在这儿,仔细查阅了API发现,在service的参数中,设置错误了,所以,在以后的开发中请注意,如果您选择的是:
标准双接口交易->service=trade_create_by_buyer
即时到帐交易->service=create_direct_pay_by_user
这里一定要填写正确,否则就会出现没有权限这样的问题,这里请注意一下。
笔者遇到的第二个问题:
支付成功了,但是总是返回的错误页面,首先请看下面的代码:
//生成Md5摘要;
string mysign = GetMD5(prestr.ToString(), _input_charset);
string sign = Request.QueryString["sign"];
if (mysign == sign && responseTxt =="true") //验证支付发过来的消息,签名是否正确
{
Response.Write("success"); //返回给支付宝消息,成功
}
else
{
Response.Write("fail");
}
这里如果mysign和responseTxt为flase,则会显示错误信息,这是由于在Return页面中,没有设置支付宝安全校验码(key)和合作伙伴id(partner),解决方法,在page_lode中加入常量:
String key = "xxxxxxxxxxxxxxxxx";//你的安全效验码
String partner = "xxxxxxxxxxxxxx";//你的合作伙伴id;
这样,加入后,当付款成功时,就会返回到正确的Success了!
笔者使用的是.net版的支付方式,Java版也许会有所不同,不过原理应该和这个是一样的,我已经下载了官方给出的Java实例,待看后与大家分享经验心得。
微软今天发布了 Net Framework 3.5 的 Chart 控件,弥补了 .Net 平台下缺乏一个十分强力的图表控件。
该图表控件支持多种图表,如饼图,柱状图,曲线图,散点图,雷达图,面积图,股票图等,同时支持 Winform 和 Asp.net。
目前该控件只能用在 .Net Framework 3.5 上,没有查找到 For .Net Framework 2.0 的信息。
补:原来该款控件来自 dundas.com,有 .Net Framework 2.0 版本,需要付费,该公司被微软收购后主推 3.5 版本,并免费。
包含英文版,中文版。上面提供的链接是中文版的,可以更改为英文版。
语言包:Microsoft Chart Controls for Microsoft .NET Framework 3.5 LanguagePack
Microsoft .NET Framework 3.5 的Microsoft 图表控件 的语言包,包含23中语言。
Microsoft Chart Controls Add-on for Microsoft Visual Studio 2008
使 VS2008 支持图表开发的插件。
WinForm 和 Asp.net 的例子(SamplesEnvironment for Microsoft Chart Controls)
这个只有英文的,没找到英文的。
2D的图:

3D的图:
1. Microsoft Chart control for .NET Framework Released!
2.图片来自 http://code.msdn.microsoft.com/mschart 中的 Winform 演示。
可以创建实现模板的用户控件,这是 ASP.NET 的一项功能,它允许将控件数据与其表示形式相分离。模板化控件不提供用户界面。编写它则是为了实现一个命名容器以及包含属性和方法可由宿主页访问的类。
用户控件的用户界面由页面开发人员在设计时提供。开发人员创建由用户控件定义的类型模板,然后可以向模板添加控件和标记。
创建模板用户控件
-
在 .ascx 文件中,添加要在其中显示模板的 ASP.NET PlaceHolder 控件。
-
在用户控件的代码中,实现 ITemplate 类型的属性。
-
将实现 INamingContainer 接口的服务器控件类定义为要在其中创建模板实例的容器。此容器叫做模板的命名容器。
说明:
此控件实质上成了用户控件的嵌套类,但这不是必需的。
-
将 TemplateContainerAttribute 应用于实现 ITemplate 的属性 (property),并将模板命名容器的类型作为参数传递给属性 (attribute) 的构造函数。
-
在控件的 Init 方法中,将以下步骤重复一次或多次:
-
创建命名容器类的一个实例。
-
在命名容器中创建该模板的一个实例。
-
将命名容器实例添加到 PlaceHolder 服务器控件的 Controls 属性。
说明:
从使用用户控件的页面的角度来看,模板化用户控件的语法与自定义模板化控件的语法相同。
-

下面的示例演示一个模板化用户控件和一个包含该控件的页面。该用户控件创建一个可在宿主页上声明为 <MessageTemplate> 的模板。该模板控件还公开两个可由宿主页在模板内访问的属性:Index 和 Message。
第一个示例显示模板化用户控件。第二个示例显示包含该用户控件的页面。
<%@ Control language="VB" ClassName="TemplatedUC" %> <%@ Import Namespace="System.ComponentModel" %> <script runat="server" > Private m_messageTemplate As ITemplate = Nothing <TemplateContainer(GetType(MessageContainer))> _ <PersistenceMode(PersistenceMode.InnerProperty)> Public Property _ MessageTemplate() As ITemplate Get Return m_messageTemplate End Get Set(ByVal value As ITemplate) m_messageTemplate = Value End Set End Property Sub Page_Init() If Not (MessageTemplate Is Nothing) Then Dim i As Integer Dim fruits() As String = _ {"apple", "orange", "banana", "pineapple"} For i = 0 To 3 Dim container As New MessageContainer(i, fruits(i)) MessageTemplate.InstantiateIn(container) PlaceHolder1.Controls.Add(container) Next i End If End Sub Public Class MessageContainer Inherits Control Implements INamingContainer Private m_index As Integer Private m_message As String Friend Sub New(ByVal i As Integer, ByVal msg As String) Me.Index = i Me.Message = msg End Sub Public Property Index() As Integer Get Return m_index End Get Set(ByVal value As Integer) m_index = value End Set End Property Public Property Message() As String Get Return m_message End Get Set(ByVal value As String) m_message = value End Set End Property End Class </script> <asp:Placeholder runat="server" ID="PlaceHolder1" />
<%@ Control language="C#" ClassName="TemplatedUC" %> <%@ Import Namespace="System.ComponentModel" %> <script runat="server"> private ITemplate messageTemplate = null; [ TemplateContainer(typeof(MessageContainer)) ] [ PersistenceMode(PersistenceMode.InnerProperty) ] public ITemplate MessageTemplate { get { return messageTemplate; } set { messageTemplate = value; } } void Page_Init() { if (messageTemplate != null) { String[] fruits = {"apple", "orange", "banana", "pineapple" }; for (int i=0; i<4; i++) { MessageContainer container = new MessageContainer(i, fruits[i]); messageTemplate.InstantiateIn(container); PlaceHolder1.Controls.Add(container); } } } public class MessageContainer: Control, INamingContainer { private int m_index; private String m_message; internal MessageContainer(int index, String message) { m_index = index; m_message = message; } public int Index { get { return m_index; } } public String Message { get { return m_message; } } } </script> <asp:Placeholder runat="server" ID="PlaceHolder1" />
<%@ Page Language="VB" %> <%@ Register TagPrefix="uc" tagname="TemplateTest" Src="TemplatedUC.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html > <script runat="server"> Sub Page_Load() DataBind() End Sub </script> <head> <title>Templated User Control Test</title> </head> <body> <h1>Testing Templated User Control</h1> <form id="Form1" runat="server"> <uc:TemplateTest runat="server"> <MessageTemplate> Index: <asp:Label runat="server" ID="Label1" Text='<%# Container.Index %>' /> <br /> Message: <asp:Label runat="server" ID="Label2" Text='<%# Container.Message %>' /> <hr /> </MessageTemplate> </uc:TemplateTest> </form> </body> </html>
<%@ Page Language="C#" %> <%@ Register TagPrefix="uc" tagname="TemplateTest" Src="TemplatedUC.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html > <script runat="server"> protected void Page_Load() { DataBind(); } </script> <head> <title>Templated User Control Test</title> </head> <body> <h1>Testing Templated User Control</h1> <form id="Form1" runat="server"> <uc:TemplateTest runat="server"> <MessageTemplate> Index: <asp:Label runat="server" ID="Label1" Text='<%# Container.Index %>' /> <br /> Message: <asp:Label runat="server" ID="Label2" Text='<%# Container.Message %>' /> <hr /> </MessageTemplate> </uc:TemplateTest> </form> </body> </html>
There are a few services out there that serve up screenshots of any webpage for you to display on your website. One popular one is Kwiboo; this is the one that DotNetKicks uses. For some time now I've wondered what the easiest way to do this in .NET was, and today I stumbled upon the undocumented WebBrowser.DrawToBitmap method that makes this extremely easy to do.
By the way, I stumbled upon the WebBrowser.DrawToBitmap while taking a look at the source code for the WebPreview tool over at SmallSharpTools.com.
Here's a sample method that returns a Bitmap representation of a webpage:
public Bitmap GenerateScreenshot(string url)
{
// This method gets a screenshot of the webpage
// rendered at its full size (height and width)
return GenerateScreenshot(url, -1, -1);
}
public Bitmap GenerateScreenshot(string url, int width, int height)
{
// Load the webpage into a WebBrowser control
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
// Set the size of the WebBrowser control
wb.Width = width;
wb.Height = height;
if (width == -1)
{
// Take Screenshot of the web pages full width
wb.Width = wb.Document.Body.ScrollRectangle.Width;
}
if (height == -1)
{
// Take Screenshot of the web pages full height
wb.Height = wb.Document.Body.ScrollRectangle.Height;
}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
return bitmap;
}
Here are some example usages of the above method:
// Generate thumbnail of a webpage at 1024x768 resolution
Bitmap thumbnail = GenerateScreenshot("http://pietschsoft.com", 1024, 768);
// Generate thumbnail of a webpage at the webpage's full size (height and width)
thumbnail = GenerateScreenshot("http://pietschsoft.com");
// Display Thumbnail in PictureBox control
pictureBox1.Image = thumbnail;
/*
// Save Thumbnail to a File
thumbnail.Save("thumbnail.png", System.Drawing.Imaging.ImageFormat.Png);
*/
我们继续讲解LINQ to SQL语句,这篇我们来讨论Group By/Having操作符和Exists/In/Any/All/Contains操作符。
Group By/Having操作符
适用场景:分组数据,为我们查找数据缩小范围。
说明:分配并返回对传入参数进行分组操作后的可枚举对象。分组;延迟
1.简单形式:
var q = from p in db.Products group p by p.CategoryID into g select g;
语句描述:使用Group By按CategoryID划分产品。
说明:from p in db.Products 表示从表中将产品对象取出来。group p by p.CategoryID into g表示对p按CategoryID字段归类。其结果命名为g,一旦重新命名,p的作用域就结束了,所以,最后select时,只能select g。当然,也不必重新命名可以这样写:
var q = from p in db.Products group p by p.CategoryID;
我们用示意图表示:
如果想遍历某类别中所有记录,这样:
foreach (var gp in q) { if (gp.Key == 2) { foreach (var item in gp) { //do something } } }
2.Select匿名类:
var q = from p in db.Products group p by p.CategoryID into g select new { CategoryID = g.Key, g };
说明:在这句LINQ语句中,有2个property:CategoryID和g。这个匿名类,其实质是对返回结果集重新进行了包装。把g的property封装成一个完整的分组。如下图所示:
如果想遍历某匿名类中所有记录,要这么做:
foreach (var gp in q) { if (gp.CategoryID == 2) { foreach (var item in gp.g) { //do something } } }
3.最大值
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, MaxPrice = g.Max(p => p.UnitPrice) };
语句描述:使用Group By和Max查找每个CategoryID的最高单价。
说明:先按CategoryID归类,判断各个分类产品中单价最大的Products。取出CategoryID值,并把UnitPrice值赋给MaxPrice。
4.最小值
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, MinPrice = g.Min(p => p.UnitPrice) };
语句描述:使用Group By和Min查找每个CategoryID的最低单价。
说明:先按CategoryID归类,判断各个分类产品中单价最小的Products。取出CategoryID值,并把UnitPrice值赋给MinPrice。
5.平均值
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
语句描述:使用Group By和Average得到每个CategoryID的平均单价。
说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的平均值。
6.求和
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, TotalPrice = g.Sum(p => p.UnitPrice) };
语句描述:使用Group By和Sum得到每个CategoryID 的单价总计。
说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的总和。
7.计数
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, NumProducts = g.Count() };
语句描述:使用Group By和Count得到每个CategoryID中产品的数量。
说明:先按CategoryID归类,取出CategoryID值和各个分类产品的数量。
8.带条件计数
var q = from p in db.Products group p by p.CategoryID into g select new { g.Key, NumProducts = g.Count(p => p.Discontinued) };
语句描述:使用Group By和Count得到每个CategoryID中断货产品的数量。
说明:先按CategoryID归类,取出CategoryID值和各个分类产品的断货数量。 Count函数里,使用了Lambda表达式,Lambda表达式中的p,代表这个组里的一个元素或对象,即某一个产品。
9.Where限制
var q = from p in db.Products group p by p.CategoryID into g where g.Count() >= 10 select new { g.Key, ProductCount = g.Count() };
语句描述:根据产品的―ID分组,查询产品数量大于10的ID和产品数量。这个示例在Group By子句后使用Where子句查找所有至少有10种产品的类别。
说明:在翻译成SQL语句时,在最外层嵌套了Where条件。
10.多列(Multiple Columns)
var categories = from p in db.Products group p by new { p.CategoryID, p.SupplierID } into g select new { g.Key, g };
语句描述:使用Group By按CategoryID和SupplierID将产品分组。
说明: 既按产品的分类,又按供应商分类。在by后面,new出来一个匿名类。这里,Key其实质是一个类的对象,Key包含两个Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍历CategoryID的值。
11.表达式(Expression)
var categories = from p in db.Products group p by new { Criterion = p.UnitPrice > 10 } into g select g;
语句描述:使用Group By返回两个产品序列。第一个序列包含单价大于10的产品。第二个序列包含单价小于或等于10的产品。
说明:按产品单价是否大于10分类。其结果分为两类,大于的是一类,小于及等于为另一类。
Exists/In/Any/All/Contains操作符
适用场景:用于判断集合中元素,进一步缩小范围。
Any
说明:用于判断集合中是否有元素满足某一条件;不延迟。(若条件为空,则集合只要不为空就返回True,否则为False)。有2种形式,分别为简单形式和带条件形式。
1.简单形式:
仅返回没有订单的客户:
var q = from c in db.Customers where !c.Orders.Any() select c;
生成SQL语句为:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0] WHERE NOT (EXISTS( SELECT NULL AS [EMPTY] FROM [dbo].[Orders] AS [t1] WHERE [t1].[CustomerID] = [t0].[CustomerID] ))
2.带条件形式:
仅返回至少有一种产品断货的类别:
var q = from c in db.Categories where c.Products.Any(p => p.Discontinued) select c;
生成SQL语句为:
SELECT [t0].[CategoryID], [t0].[CategoryName], [t0].[Description], [t0].[Picture] FROM [dbo].[Categories] AS [t0] WHERE EXISTS( SELECT NULL AS [EMPTY] FROM [dbo].[Products] AS [t1] WHERE ([t1].[Discontinued] = 1) AND ([t1].[CategoryID] = [t0].[CategoryID]) )
All
说明:用于判断集合中所有元素是否都满足某一条件;不延迟
1.带条件形式
var q = from c in db.Customers where c.Orders.All(o => o.ShipCity == c.City) select c;
语句描述:这个例子返回所有订单都运往其所在城市的客户或未下订单的客户。
Contains
说明:用于判断集合中是否包含有某一元素;不延迟。它是对两个序列进行连接操作的。
string[] customerID_Set = new string[] { "AROUT", "BOLID", "FISSA" }; var q = ( from o in db.Orders where customerID_Set.Contains(o.CustomerID) select o).ToList();
语句描述:查找"AROUT", "BOLID" 和 "FISSA" 这三个客户的订单。 先定义了一个数组,在LINQ to SQL中使用Contains,数组中包含了所有的CustomerID,即返回结果中,所有的CustomerID都在这个集合内。也就是in。 你也可以把数组的定义放在LINQ to SQL语句里。比如:
var q = ( from o in db.Orders where ( new string[] { "AROUT", "BOLID", "FISSA" }) .Contains(o.CustomerID) select o).ToList();
Not Contains则取反:
var q = ( from o in db.Orders where !( new string[] { "AROUT", "BOLID", "FISSA" }) .Contains(o.CustomerID) select o).ToList();
1.包含一个对象:
var order = (from o in db.Orders where o.OrderID == 10248 select o).First(); var q = db.Customers.Where(p => p.Orders.Contains(order)).ToList(); foreach (var cust in q) { foreach (var ord in cust.Orders) { //do something } }
语句描述:这个例子使用Contain查找哪个客户包含OrderID为10248的订单。
2.包含多个值:
string[] cities = new string[] { "Seattle", "London", "Vancouver", "Paris" }; var q = db.Customers.Where(p=>cities.Contains(p.City)).ToList();
语句描述:这个例子使用Contains查找其所在城市为西雅图、伦敦、巴黎或温哥华的客户。
总结一下这篇我们说明了以下语句:
Group By/Having | 分组数据;延迟 |
Any | 用于判断集合中是否有元素满足某一条件;不延迟 |
All | 用于判断集合中所有元素是否都满足某一条件;不延迟 |
Contains | 用于判断集合中是否包含有某一元素;不延迟 |
本系列链接:LINQ体验系列文章导航
LINQ推荐资源
LINQ专题:http://kb.cnblogs.com/zt/linq/ 关于LINQ方方面面的入门、进阶、深入的文章。
LINQ小组:http://space.cnblogs.com/group/linq/ 学习中遇到什么问题或者疑问提问的好地方。
Earlier this summer I started writing a multi-part blog series that discusses the built-in LINQ to SQL provider in .NET 3.5. LINQ to SQL is an ORM (object relational mapping) implementation that allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it. LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate data validation and business logic rules into your data model.
You can learn more about LINQ to SQL by reading my posts below (more will be coming soon):
- Part 1: Introduction to LINQ to SQL
- Part 2: Defining our Data Model Classes
- Part 3: Querying our Database
- Part 4: Updating our Database
- Part 5: Binding UI using the ASP:LinqDataSource Control
Using the LINQ to SQL Debug Visualizer
One of the nice development features that LINQ to SQL supports is the ability to use a "debug visualizer" to hover over a LINQ expression while in the VS 2008 debugger and inspect the raw SQL that the ORM will ultimately execute at runtime when evaluating the LINQ query expression.
For example, assume we write the below LINQ query expression code against a set of data model classes:
We could then use the VS 2008 debugger to hover over the "products" variable after the query expression has been assigned:
And if we click the small magnifying glass in the expression above, we can launch the LINQ to SQL debug visualizer to inspect the raw SQL that the ORM will execute based on that LINQ query:
If you click the "Execute" button, you can even test out the SQL query and see the raw returned results that will be returned from the database:
This obviously makes it super easy to see precisely what SQL query logic LINQ to SQL ORM is doing for you.
You can learn even more about how all this works by reading the Part 3: Querying our Database segment in my LINQ to SQL series above.
How to Install the LINQ to SQL Debug Visualizer
The LINQ to SQL Debug Visualizer isn't built-in to VS 2008 - instead it is an add-in that you need to download to use. You can download a copy of it here.
The download contains both a binary .dll assembly version of the visualizer (within the \bin\debug directory below), as well as all of the source code for the visualizer:
To install the LINQ to SQL debug visualizer, follow the below steps:
1) Shutdown all running versions of Visual Studio 2008
2) Copy the SqlServerQueryVisualizer.dll assembly from the \bin\debug\ directory in the .zip download above into your local \Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers\ directory:
3) Start up Visual Studio 2008 again. Now when you use the debugger with LINQ to SQL you should be able to hover over LINQ query expressions and inspect their raw SQL (no extra registration is required).
Hope this helps,
Scott
今年早些时候,我通过blog介绍了 C# 和 VB 语言的一项新的扩充特性"扩展方法"。
扩展方法让开发者可以向已有的 CLR 类型的公共契约中添加新的方法,而不需要子类化或重新编译原有的类型。通过这种做法,可以使很多有用的应用场景成为可能(包括 LINQ)。同时,扩展方法也可以用来非常方便地向代码中添加"语法糖"。
过去几个月,我一直在准备一些很酷的扩展方法的清单,并计划在有空的时候实现它们(不确定何时...但至少我还能从这些想法中获得乐趣)。在上述清单中有两个扩展方法的应用场景,分别是用于为任意 .NET 对象自动生成JSON (JavaScript Object Notation)或 XML 序列化字符串的。
简单场景:ToJSON() 扩展方法
假设我有一个 Person 类定义如下(注意:我使用了 自动属性的新特性来实现):
接下来,我就可以初始化一系列 Person 对象的集合,然后只需调用 ToJSON() 扩展方法,就能得到表示该集合内容的 JSON 字符串。如下所示:
这和 .NET 中内建的,Object 类的 ToString() 方法调用方式很相似 —— 只是生成的结果是表示集合内容的 JSON 格式的字符串而已。然后我们就可以在 AJAX 场景的客户端使用它:
注意:点击上图中调试器的放大镜图标,可以打开"文本视图(Text Visualizer)",能更方便的查看 JSON 序列化字符串:
接下来,这个字符串格式在客户端可以用 JavaScript 来实例化为合适的 JavaScript 对象,用于表示我的集合内容(注: ASP.NET AJAX 有一个内建的 JavaScript 库支持这些特性)。
实现 ToJSON 扩展方法
实现一个基本的 ToJSON() 扩展方法很简单。只要使用 System.Web.Script.Serialization 命名空间下的 JavaScriptSerializer 类即可,然后象下面所示的那样定义两个扩展方法。其中一个方法用于对目标对象图(object graph)进行"深"的序列化,而另一个方法则是一个重载的版本,它允许你指定序列化的深度(比如:ToJSON(2) 只序列化 2 个层次的深度)。
注意,上面的 ToJSON() 扩展方法只是针对 "Object" 类型而定义的——这意味着它可以被用于 .NET 中的任何类型(不限于集合)。也就是说,我们不仅能对上述集合调用 .ToJSON() 方法,还可以对单独的 Person 对象调用 ToJSON() 方法,或者任意其他的 .NET 类型都可以。
要使用上述扩展方法,只需在程序的顶部添加如下命名空间的引用即可:
然后 VS 2008 就可以为任意对象提供针对这些扩展方法的代码自动完成和编译时支持功能:
注意:除了 JavaScriptSerializer 类之外,.NET 3.5 还包含一个新的new System.Runtime.Serialization.DataContractJsonSerializer class 类 ,你也可以用它来做 JSON 序列化/反序列化的工作。
小结
希望以上的例子能给你一个使用扩展方法来封装功能的示例。下次希望我们一起来看一些好的工具库,用于提供类似有用的扩展方法的功能。
我非常想看到其他关于可复用的扩展方法使用场景的建议(请通过这篇帖子的评论来建议)。然后我们可以琢磨出,如何创建一个好的 CodePlex 项目,来把这些方法捆绑到一个库中以便利用。
希望这篇帖子对你有用,
Scott