Linq To Object实例之过滤字符集
目前利用Linq To Object可以查询实现了IEnumerable<T>接口的未定义类型对象数组、自定义对象数组、泛型List和Dictionary、以及string等。当然进行编程之前要添加System.Core.dll引用和命名空间System.Linq,事实上VS2008已经在建立项目的时候自动添加了。
这次要做的是一个简单的winform程序主要用Linq to object来过滤字符集,然后绑定到相应的datagrid去。
先来看看完成后的效果图(通过鼠标点击改变测试字符集):
本实例省略调试代码!主要Linq实现步骤简述如下:
定义系统字符集![](/Images/OutliningIndicators/None.gif)
private List<FontFamily> systemFont = new List<FontFamily>();
![](/Images/OutliningIndicators/None.gif)
private List<FontFamily> systemFont = new List<FontFamily>();
1
/// <summary>
2
/// 获取已安装的字符集
3
/// </summary>
4
/// <returns>字符集list</returns>
5
private List<FontFamily> GetAllFont()
6
{
7![](/Images/OutliningIndicators/InBlock.gif)
8
foreach (FontFamily f in FontFamily.Families)
9
{
10
systemFont.Add(new FontFamily(f.Name));
11![](/Images/OutliningIndicators/InBlock.gif)
12
}
13
return systemFont;
14
}
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
2
![](/Images/OutliningIndicators/InBlock.gif)
3
![](/Images/OutliningIndicators/InBlock.gif)
4
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
5
![](/Images/OutliningIndicators/None.gif)
6
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
7
![](/Images/OutliningIndicators/InBlock.gif)
8
![](/Images/OutliningIndicators/InBlock.gif)
9
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
10
![](/Images/OutliningIndicators/InBlock.gif)
11
![](/Images/OutliningIndicators/InBlock.gif)
12
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
13
![](/Images/OutliningIndicators/InBlock.gif)
14
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
1
通过查询把结果集绑定到datagrid中去
var query
2
= from font in systemFont
3
where font.Name.ToLower().StartsWith(txtFontFilter.Text.ToLower())&&font.IsStyleAvailable(FontStyle.Regular)
4
select font;
5
//Gray Zhang给了很好的建议font.IsStyleAvailable(FontStyle.Regular),在此感谢!
6
dgvFont.DataSource = query.ToList();//这里的ToList是必须的,为了在winform中生成List进行显示. ASP.net有所不同.
![](/Images/OutliningIndicators/None.gif)
var query
2
![](/Images/OutliningIndicators/None.gif)
3
![](/Images/OutliningIndicators/None.gif)
4
![](/Images/OutliningIndicators/None.gif)
5
![](/Images/OutliningIndicators/None.gif)
6
![](/Images/OutliningIndicators/None.gif)
可能遇到的问题: 字体"......"不支持样式"Regular",也许是由于系统字体库出了问题,更新一下.如果有更好的解决该Exception方法,请各位贴出来,谢谢!
附件