大家好,
Employee[] empCollection =
new Employee[]{
new Employee()
{
Name = "Test1",
Salry = "1000",
Notes = new string[] { "A","B","C","D"}
},
new Employee()
{
Name = "Test2",
Salry = "2000",
Notes = new string[] { "E","F","G","H"}
}
};
var data = from e in empCollection
from n in e.Notes
select new { Name = e.Name, note = n };
测试1:乙 测试1:C 测试1:d 测试2:电子 测试2:F 测试2:g ^ TEST2:H
我想知道基于此查询的基于synatx的等效方法吗?
我试过这个
var data = empCollection.Select(
e =>
e.Notes.Select(n => new
{
name = e.Name,
note = n
}
)
);
但是我无法在foreach循环中获得名称和注释为什么?
感谢。
答案 0 :(得分:3)
您的代码返回IEnumerable<IEnumerable<T>>
,您需要使用SelectMany
来“展平”&#39;您的结果为IEnumerable<T>
:
var data = empCollection
.SelectMany(e => e.Notes.Select(n => new {name = e.Name, note = n}));
Per the documentation,您的原始编译器从查询到方法语法完成的机械翻译使用SelectMany
的重载,创建一个匿名类型来配对这两个项目,以便它们可以在投影(注意,由于编译器发明的变量名称,这实际上不会编译):
var data = empCollection
.SelectMany(e => e.Notes, (e, n) => new {e, n})
.Select($1 => new { name = $1.e.Name, note = $1.n });
当然,这可以简化,你最终会在编译器生成的代码和原始代码之间的某处:
var data = empCollection
.SelectMany(e => e.Notes, (e, n) => new {name = e.Name, note = n});
请参阅this fiddle了解演示。