《C#本质论》读书笔记(15)使用查询表达式的LINQ
Posted 【唐】三三
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《C#本质论》读书笔记(15)使用查询表达式的LINQ相关的知识,希望对你有一定的参考价值。
15.1 查询表达式的概念
private static void ShowContextualKeywords1()
{
IEnumerable<string> selection = from word in Keywords
where !word.Contains(\'*\')
select word;
foreach (string keyword in selection)
{
Console.Write(" " + keyword);
}
}
private static string[] Keywords = {
"abstract", "add*", "alias*", "as", "ascending*", "base",
"bool", "break", "by*", "byte", "case", "catch", "char",
"checked", "class", "const", "continue", "decimal",
"default", "delegate", "descending*", "do", "double",
"dynamic*", "else", "enum", "event", "equals*",
"explicit", "extern", "false", "finally", "fixed",
"from*", "float", "for", "foreach", "get*", "global*",
"group*", "goto", "if", "implicit", "in", "int",
"into*", "interface", "internal", "is", "lock", "long",
"join*", "let*", "namespace", "new", "null", "object",
"on*", "operator", "orderby*", "out", "override",
"params", "partial*", "private", "protected", "public",
"readonly", "ref", "remove*", "return", "sbyte", "sealed",
"select*", "set*", "short", "sizeof", "stackalloc",
"static", "string", "struct", "switch", "this", "throw",
"true", "try", "typeof", "uint", "ulong", "unchecked",
"unsafe", "ushort", "using", "value*", "var*", "virtual",
"void", "volatile", "where*", "while", "yield*"
};
15.1.1 投射
IEnumerbale<T>
或 IQueryable<T>
集合。T数据类型是从select或者groupby子句推导。select word
推导的,因为word是一个字符串。word数据类型是由from
子句所指定的IEnumerbale<T>集合的类型参数(这里是Keywords)。由于Keywords是一个string数组,它实现了IEnumerbale<T>
,所以word是一个字符串。public static void Main()
{
List1(Directory.GetCurrentDirectory(),"*");
}
static void List1(string rootDirectory, string searchPattern)
{
IEnumerable<FileInfo> files =
from fileName in Directory.GetFiles(
rootDirectory, searchPattern)
select new FileInfo(fileName);
foreach (FileInfo file in files)
{
Console.WriteLine(".{0} ({1})",
file.Name, file.LastWriteTime);
}
}
IEnumerable<FileInfo>
,而不是System.IO.Directory.GetFiles()
返回的IEnumerables<string>
数据类型。var files =
from fileName in Directory.GetFiles(
rootDirectory, searchPattern)
select new FileInfo(fileName);
15.1.2 筛选
IEnumerable<string> selection = from word in Keywords
where !word.Contains(\'*\')
select word;
15.1.3 排序
IEnumerable<string> fileNames =
from fileName in Directory.GetFiles(
rootDirectory, searchPattern)
orderby (new FileInfo(fileName)).Length descending,
fileName
select fileName;
15.1.4 let子句
public static void Main()
{
ListByFileSize2(Directory.GetCurrentDirectory(), "*");
}
static void ListByFileSize2(
string rootDirectory, string searchPattern)
{
IEnumerable<FileInfo> files =
from fileName in Directory.GetFiles(
rootDirectory, searchPattern)
orderby new FileInfo(fileName).Length, fileName
select new FileInfo(fileName);
foreach (FileInfo file in files)
{
// As simplification, current directory is
以上是关于《C#本质论》读书笔记(15)使用查询表达式的LINQ的主要内容,如果未能解决你的问题,请参考以下文章