虽然在少数情况下我会使用方法链编写一些东西(特别是如果它只有一两个方法,比如 foo.Where(..).ToArray()),但在许多情况下,我更喜欢 LINQ 查询理解语法而是(规范中的“查询表达式”),例如:
var query =
from filePath in Directory.GetFiles(directoryPath)
let fileName = Path.GetFileName(filePath)
let baseFileName = fileName.Split(' ', '_').First()
group filePath by baseFileName into fileGroup
select new
{
BaseFileName = fileGroup.Key,
Count = fileGroup.Count(),
};
在其中一些相当大的块中,我需要获取生成的 IEnumerable 并将其急切加载到数据结构(数组、列表等)中。这通常意味着:
添加另一个局部变量,例如 var queryResult = query.ToArray(); 或者
用括号包装查询并在 ToArray (或 ToList 或其他)上标记。
var query = (
from filePath in Directory.GetFiles(directoryPath)
let fileName = Path.GetFileName(filePath)
let baseFileName = fileName.Split(' ', '_').First()
group filePath by baseFileName into fileGroup
select new
{
BaseFileName = fileGroup.Key,
Count = fileGroup.Count(),
}
).ToArray();
我试图找出其他人正在使用的选项 1) 已经在使用或 2) 可以认为添加一些额外的“上下文关键字”是可行的——只是可以像现有方法一样转换为扩展方法的东西,好像 LINQ 关键字是“本机”可扩展的 :)
我意识到这很可能意味着某种预处理(不确定 C# 在这个领域中有什么)或将编译器更改为Nemerle之类的东西(我认为这是一个选项,但不太确定? )。我还不太了解 Roslyn 所做/将支持什么,所以如果有人知道它是否可以允许某人像这样“扩展”C#,请插话!
我可能会使用最多的那些(虽然我确信还有很多其他的,但只是为了理解这个想法/我希望的是什么):
ascount - 转换为 Count()
int zFileCount =
from filePath in Directory.GetFiles(directoryPath)
where filePath.StartsWith("z")
select filePath ascount;
这将“转换”(无论路径是什么,只要最终结果是)为:
int zFileCount = (
from filePath in Directory.GetFiles(directoryPath)
where filePath.StartsWith("z")
select filePath
).Count();
相似地:
- asarray - 转换为 ToArray()
- aslist - 转换为 ToList()
(您显然可以继续使用 First()、Single()、Any() 等,但要控制问题范围 :)
我只对不需要传递参数的扩展方法感兴趣。我不想尝试用(例如)ToDictionary 或 ToLookup 来做这种事情。:)
所以,总结一下:
- 想要将“ascount”、“aslist”和“asarray”添加到 linq 查询表达式中
- 不知道这是否已经解决
- 不知道 Nemerle 是否是一个不错的选择
- 不知道 Roslyn 的故事是否会支持这种用法